https://github.com/soulmachine/machine-learning-cheat-sheet
soulmachine@gmail.com

Machine Learning Cheat Sheet

Classical equations, diagrams and tricks in machine learning

February 12, 2015

ii

©2013 soulmachine
Except where otherwise noted, This document is licensed under a Creative Commons Attribution-ShareAlike 3.0
Unported (CC BY-SA3.0) license
(http://creativecommons.org/licenses/by/3.0/).

Preface

This cheat sheet contains many classical equations and diagrams on machine learning, which will help you quickly
recall knowledge and ideas in machine learning.

This cheat sheet has three signiﬁcant advantages:

1. Strong typed. Compared to programming languages, mathematical formulas are weakly typed. For example, X can
be a set, a random variable, or a matrix. This causes difﬁculty in understanding the meaning of formulas. In this
cheat sheet, I try my best to standardize symbols used, see section §.

2. More parentheses. In machine learning, authors are prone to omit parentheses, brackets and braces, this usually
causes ambiguity in mathematical formulas. In this cheat sheet, I use parentheses(brackets and braces) at where
they are needed, to make formulas easy to understand.

3. Less thinking jumps. In many books, authors are prone to omit some steps that are trivial in his option. But it often

makes readers get lost in the middle way of derivation.

At Tsinghua University, May 2013

soulmachine

iii

Contents

Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

v

2.5.3 Multivariate Student’s

Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

1

2

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Types of machine learning . . . . . . . . . . . .
1.1
Three elements of a machine learning
1.2
model . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Representation . . . . . . . . . . . . . .
1.2.1
Evaluation . . . . . . . . . . . . . . . . .
1.2.2
1.2.3
Optimization . . . . . . . . . . . . . . .
Some basic concepts . . . . . . . . . . . . . . . . .
1.3.1

1.3

1.3.2

Parametric vs non-parametric
models . . . . . . . . . . . . . . . . . . . .
A simple non-parametric
classiﬁer: K-nearest neighbours
Overﬁtting . . . . . . . . . . . . . . . . .
1.3.3
1.3.4
Cross validation . . . . . . . . . . . . .
1.3.5 Model selection . . . . . . . . . . . . .

Probability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Frequentists vs. Bayesians . . . . . . . . . . . .
2.1
A brief review of probability theory . . . .
2.2
2.2.1
Basic concepts . . . . . . . . . . . . . .
2.2.2 Mutivariate random variables . .
Bayes rule . . . . . . . . . . . . . . . . . .
2.2.3
Independence and conditional
2.2.4
independence . . . . . . . . . . . . . . .
2.2.5
Quantiles . . . . . . . . . . . . . . . . . .
2.2.6 Mean and variance . . . . . . . . . .
Some common discrete distributions . . .
2.3.1

2.3

2.3.2

The Bernoulli and binomial
distributions . . . . . . . . . . . . . . . .
The multinoulli and
multinomial distributions . . . . .
The Poisson distribution . . . . . .
2.3.3
2.3.4
The empirical distribution . . . .
Some common continuous distributions .
Gaussian (normal) distribution .
2.4.1
Student’s t-distribution . . . . . . .
2.4.2
The Laplace distribution . . . . . .
2.4.3
The gamma distribution . . . . . .
2.4.4
2.4.5
The beta distribution . . . . . . . . .
Pareto distribution . . . . . . . . . . .
2.4.6
Joint probability distributions . . . . . . . . .
2.5.1
Covariance and correlation . . . .
2.5.2 Multivariate Gaussian

2.4

2.5

1
1

1
1
1
2
2

2

2
2
2
2

3
3
3
3
3
4

4
4
4
5

5

5
5
5
6
6
6
7
8
8
8
9
9

distribution . . . . . . . . . . . . . . . . . 10

2.6

t-distribution . . . . . . . . . . . . . . . 10
2.5.4
Dirichlet distribution . . . . . . . . . 10
Transformations of random variables . . . 11
Linear transformations . . . . . . . 11
2.6.1
General transformations . . . . . . 11
2.6.2
Central limit theorem . . . . . . . . 13
2.6.3
2.7 Monte Carlo approximation . . . . . . . . . . . 13
Information theory . . . . . . . . . . . . . . . . . . 14
2.8
Entropy . . . . . . . . . . . . . . . . . . . . 14
2.8.1
2.8.2
KL divergence . . . . . . . . . . . . . . 14
2.8.3 Mutual information . . . . . . . . . . 14

3.3

3.1
3.2

3 Generative models for discrete data . . . . . . . . 17
Generative classiﬁer . . . . . . . . . . . . . . . . . 17
Bayesian concept learning . . . . . . . . . . . . 17
Likelihood . . . . . . . . . . . . . . . . . 17
3.2.1
Prior . . . . . . . . . . . . . . . . . . . . . . 17
3.2.2
Posterior . . . . . . . . . . . . . . . . . . . 17
3.2.3
3.2.4
Posterior predictive distribution 18
The beta-binomial model . . . . . . . . . . . . . 18
Likelihood . . . . . . . . . . . . . . . . . 18
3.3.1
Prior . . . . . . . . . . . . . . . . . . . . . . 18
3.3.2
Posterior . . . . . . . . . . . . . . . . . . . 18
3.3.3
3.3.4
Posterior predictive distribution 19
The Dirichlet-multinomial model . . . . . . 19
Likelihood . . . . . . . . . . . . . . . . . 20
3.4.1
Prior . . . . . . . . . . . . . . . . . . . . . . 20
3.4.2
Posterior . . . . . . . . . . . . . . . . . . . 20
3.4.3
Posterior predictive distribution 20
3.4.4
Naive Bayes classiﬁers . . . . . . . . . . . . . . . 20
Optimization . . . . . . . . . . . . . . . 21
3.5.1
Using the model for prediction
3.5.2
21
The log-sum-exp trick . . . . . . . . 21
3.5.3
Feature selection using
3.5.4
mutual information . . . . . . . . . . 22
Classifying documents using
bag of words . . . . . . . . . . . . . . . 22

3.5.5

3.5

3.4

4.1

4 Gaussian Models . . . . . . . . . . . . . . . . . . . . . . . . . 25
Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.1.1 MLE for a MVN . . . . . . . . . . . . 25
4.1.2 Maximum entropy derivation

4.2

of the Gaussian * . . . . . . . . . . . . 26
Gaussian discriminant analysis . . . . . . . . 26
4.2.1

Quadratic discriminant
analysis (QDA) . . . . . . . . . . . . . 26

v

vi

5

4.2.2

Linear discriminant analysis
(LDA) . . . . . . . . . . . . . . . . . . . . . 27
4.2.3
Two-class LDA . . . . . . . . . . . . . 28
4.2.4 MLE for discriminant analysis . 28
Strategies for preventing
4.2.5
overﬁtting . . . . . . . . . . . . . . . . . . 29
Regularized LDA * . . . . . . . . . . 29
Diagonal LDA . . . . . . . . . . . . . . 29
Nearest shrunken centroids
classiﬁer * . . . . . . . . . . . . . . . . . 29

4.2.6
4.2.7
4.2.8

4.3

4.4

4.5
4.6

Inference in jointly Gaussian
distributions . . . . . . . . . . . . . . . . . . . . . . . . 29
Statement of the result . . . . . . . 29
4.3.1
4.3.2
Examples . . . . . . . . . . . . . . . . . . 30
Linear Gaussian systems . . . . . . . . . . . . . 30
Statement of the result . . . . . . . 30
4.4.1
Digression: The Wishart distribution * . . 30
Inferring the parameters of an MVN . . . 30
Posterior distribution of m . . . . 30
4.6.1
Posterior distribution of S * . . . 30
4.6.2
Posterior distribution of m
4.6.3
and S * . . . . . . . . . . . . . . . . . . . . 30
Sensor fusion with unknown
precisions * . . . . . . . . . . . . . . . . 30

4.6.4

5.3

Bayesian statistics . . . . . . . . . . . . . . . . . . . . . . . . 31
Introduction . . . . . . . . . . . . . . . . . . . . . . . . 31
5.1
Summarizing posterior distributions . . . . 31
5.2
5.2.1 MAP estimation . . . . . . . . . . . . . 31
Credible intervals . . . . . . . . . . . 32
5.2.2
Inference for a difference in
5.2.3
proportions . . . . . . . . . . . . . . . . . 33
Bayesian model selection . . . . . . . . . . . . . 33
Bayesian Occam’s razor . . . . . . 33
5.3.1
Computing the marginal
5.3.2
likelihood (evidence) . . . . . . . . . 34
Bayes factors . . . . . . . . . . . . . . . 36
5.3.3
Priors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Uninformative priors . . . . . . . . . 36
5.4.1
5.4.2
Robust priors . . . . . . . . . . . . . . . 36
5.4.3 Mixtures of conjugate priors . . 36
Hierarchical Bayes . . . . . . . . . . . . . . . . . . 36
Empirical Bayes . . . . . . . . . . . . . . . . . . . . 36
Bayesian decision theory . . . . . . . . . . . . . 36
5.7.1

5.5
5.6
5.7

5.4

Bayes estimators for common
loss functions . . . . . . . . . . . . . . . 37
The false positive vs false
negative tradeoff . . . . . . . . . . . . 38

5.7.2

6

Frequentist statistics . . . . . . . . . . . . . . . . . . . . . . 39
Sampling distribution of an estimator . . . 39
6.1
Bootstrap . . . . . . . . . . . . . . . . . . 39
6.1.1
Large sample theory for the
6.1.2
MLE * . . . . . . . . . . . . . . . . . . . . 39

7

8

Preface

6.2
6.3
6.4

6.5

Frequentist decision theory . . . . . . . . . . . 39
Desirable properties of estimators . . . . . . 39
Empirical risk minimization . . . . . . . . . . 39
Regularized risk minimization . 39
6.4.1
Structural risk minimization . . . 39
6.4.2
Estimating the risk using
6.4.3
cross validation . . . . . . . . . . . . . 39
Upper bounding the risk
using statistical learning
theory * . . . . . . . . . . . . . . . . . . . . 39
6.4.5
Surrogate loss functions . . . . . . 39
Pathologies of frequentist statistics * . . . 39

6.4.4

7.4

Linear Regression . . . . . . . . . . . . . . . . . . . . . . . . 41
Introduction . . . . . . . . . . . . . . . . . . . . . . . . 41
7.1
7.2
Representation . . . . . . . . . . . . . . . . . . . . . . 41
7.3 MLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
OLS . . . . . . . . . . . . . . . . . . . . . . 41
7.3.1
7.3.2
SGD . . . . . . . . . . . . . . . . . . . . . . 42
Ridge regression(MAP) . . . . . . . . . . . . . . 42
Basic idea . . . . . . . . . . . . . . . . . . 43
7.4.1
Numerically stable
7.4.2
computation * . . . . . . . . . . . . . . 43
Connection with PCA * . . . . . . 43
Regularization effects of big
data . . . . . . . . . . . . . . . . . . . . . . . 43
Bayesian linear regression . . . . . . . . . . . . 43

7.4.3
7.4.4

7.5

Logistic Regression . . . . . . . . . . . . . . . . . . . . . . . 45
Representation . . . . . . . . . . . . . . . . . . . . . . 45
8.1
Optimization . . . . . . . . . . . . . . . . . . . . . . . 45
8.2
8.2.1 MLE . . . . . . . . . . . . . . . . . . . . . . 45
8.2.2 MAP . . . . . . . . . . . . . . . . . . . . . . 45
8.3 Multinomial logistic regression . . . . . . . . 45
8.3.1
Representation . . . . . . . . . . . . . . 45
8.3.2 MLE . . . . . . . . . . . . . . . . . . . . . . 46
8.3.3 MAP . . . . . . . . . . . . . . . . . . . . . . 46
Bayesian logistic regression . . . . . . . . . . 46
Laplace approximation . . . . . . . 47
8.4.1
Derivation of the BIC . . . . . . . . 47
8.4.2
Gaussian approximation for
8.4.3
logistic regression . . . . . . . . . . . 47
Approximating the posterior
predictive . . . . . . . . . . . . . . . . . . 47
Residual analysis (outlier
detection) * . . . . . . . . . . . . . . . . 47

8.4.5

8.4.4

8.4

8.5

8.6

Online learning and stochastic
optimization . . . . . . . . . . . . . . . . . . . . . . . . 47
8.5.1
The perceptron algorithm . . . . . 47
Generative vs discriminative classiﬁers . 48
Pros and cons of each approach 48
8.6.1
Dealing with missing data . . . . 48
8.6.2
Fishers linear discriminant
8.6.3
analysis (FLDA) * . . . . . . . . . . . 50

Preface

9 Generalized linear models and the

exponential family . . . . . . . . . . . . . . . . . . . . . . . 51
The exponential family . . . . . . . . . . . . . . . 51
9.1
Deﬁnition . . . . . . . . . . . . . . . . . . 51
9.1.1
Examples . . . . . . . . . . . . . . . . . . 51
9.1.2
9.1.3
Log partition function . . . . . . . . 52
9.1.4 MLE for the exponential family 53
Bayes for the exponential
9.1.5
family . . . . . . . . . . . . . . . . . . . . . 53

9.1.6 Maximum entropy derivation

9.2

of the exponential family * . . . . 53
Generalized linear models (GLMs) . . . . . 53
9.2.1
Basics . . . . . . . . . . . . . . . . . . . . . 53
9.3
Probit regression . . . . . . . . . . . . . . . . . . . . 53
9.4 Multi-task learning . . . . . . . . . . . . . . . . . . 53

10.1

10 Directed graphical models (Bayes nets) . . . . . 55
Introduction . . . . . . . . . . . . . . . . . . . . . . . . 55
10.1.1 Chain rule . . . . . . . . . . . . . . . . . . 55
10.1.2 Conditional independence . . . . 55
10.1.3 Graphical models . . . . . . . . . . . . 55
10.1.4 Directed graphical model . . . . . 55
10.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . 56
10.2.1 Naive Bayes classiﬁers . . . . . . . 56
10.2.2 Markov and hidden Markov

models . . . . . . . . . . . . . . . . . . . . 56
10.3
Inference . . . . . . . . . . . . . . . . . . . . . . . . . . 56
10.4 Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
10.4.1 Learning from complete data . . 56
10.4.2 Learning with missing and/or

latent variables . . . . . . . . . . . . . . 57

10.5 Conditional independence properties

of DGMs . . . . . . . . . . . . . . . . . . . . . . . . . . 57
d-separation and the Bayes
10.5.1
Ball algorithm (global
Markov properties) . . . . . . . . . . 57

10.5.2 Other Markov properties of

DGMs . . . . . . . . . . . . . . . . . . . . . 57

10.5.3 Markov blanket and full

conditionals . . . . . . . . . . . . . . . . 57
10.5.4 Multinoulli Learning . . . . . . . . . 57
Inﬂuence (decision) diagrams * . . . . . . . 57

10.6

11 Mixture models and the EM algorithm . . . . . 59
11.1 Latent variable models . . . . . . . . . . . . . . . 59
11.2 Mixture models . . . . . . . . . . . . . . . . . . . . . 59
11.2.1 Mixtures of Gaussians . . . . . . . 59
11.2.2 Mixtures of multinoullis . . . . . . 60
11.2.3 Using mixture models for

clustering . . . . . . . . . . . . . . . . . . 60
11.2.4 Mixtures of experts . . . . . . . . . . 60
11.3 Parameter estimation for mixture models 60
11.3.1 Unidentiﬁability . . . . . . . . . . . . 60

vii

11.3.2 Computing a MAP estimate

is non-convex . . . . . . . . . . . . . . . 60
11.4 The EM algorithm . . . . . . . . . . . . . . . . . . 60
Introduction . . . . . . . . . . . . . . . . 60
11.4.1
11.4.2 Basic idea . . . . . . . . . . . . . . . . . . 62
11.4.3 EM for GMMs . . . . . . . . . . . . . . 62
11.4.4 EM for K-means . . . . . . . . . . . . 64
11.4.5 EM for mixture of experts . . . . 64
11.4.6 EM for DGMs with hidden

variables . . . . . . . . . . . . . . . . . . . 64

11.4.7 EM for the Student

distribution * . . . . . . . . . . . . . . . 64
11.4.8 EM for probit regression * . . . . 64
11.4.9 Derivation of the Q function . . 64
11.4.10 Convergence of the EM

Algorithm * . . . . . . . . . . . . . . . . 65

11.4.11 Generalization of EM

Algorithm * . . . . . . . . . . . . . . . . 65
11.4.12 Online EM . . . . . . . . . . . . . . . . . 66
11.4.13 Other EM variants * . . . . . . . . . 66

11.5 Model selection for latent variable

models . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
11.5.1 Model selection for

probabilistic models . . . . . . . . . 67

11.5.2 Model selection for

non-probabilistic methods . . . . 67
11.6 Fitting models with missing data . . . . . . 67
11.6.1 EM for the MLE of an MVN

with missing data . . . . . . . . . . . . 67

12.1.1

12 Latent linear models . . . . . . . . . . . . . . . . . . . . . . 69
12.1 Factor analysis . . . . . . . . . . . . . . . . . . . . . 69
FA is a low rank
parameterization of an MVN . . 69
12.1.2
Inference of the latent factors . . 69
12.1.3 Unidentiﬁability . . . . . . . . . . . . 70
12.1.4 Mixtures of factor analysers . . . 70
12.1.5 EM for factor analysis models . 71
12.1.6

Fitting FA models with
missing data . . . . . . . . . . . . . . . . 71
12.2 Principal components analysis (PCA) . . 71
12.2.1 Classical PCA . . . . . . . . . . . . . . 71
12.2.2

Singular value decomposition
(SVD) . . . . . . . . . . . . . . . . . . . . . 72
12.2.3
Probabilistic PCA . . . . . . . . . . . 73
12.2.4 EM algorithm for PCA . . . . . . . 74

12.3 Choosing the number of latent

dimensions . . . . . . . . . . . . . . . . . . . . . . . . . 74
12.3.1 Model selection for FA/PPCA . 74
12.3.2 Model selection for PCA . . . . . 74
12.4 PCA for categorical data . . . . . . . . . . . . . 74
12.5 PCA for paired and multi-view data . . . . 75

12.5.1

Supervised PCA (latent
factor regression) . . . . . . . . . . . . 75

viii

12.6

12.5.2 Discriminative supervised PCA 75
12.5.3 Canonical correlation analysis . 75
Independent Component Analysis (ICA) 75
12.6.1 Maximum likelihood estimation 75
12.6.2 The FastICA algorithm . . . . . . . 76
12.6.3 Using EM . . . . . . . . . . . . . . . . . . 76
12.6.4 Other estimation principles * . . 76

16 Adaptive basis function models . . . . . . . . . . . . 89
16.1 AdaBoost . . . . . . . . . . . . . . . . . . . . . . . . . . 89
16.1.1 Representation . . . . . . . . . . . . . . 89
16.1.2 Evaluation . . . . . . . . . . . . . . . . . 89
16.1.3 Optimization . . . . . . . . . . . . . . . 89
16.1.4 The upper bound of the

training error of AdaBoost . . . . 89

Preface

13 Sparse linear models . . . . . . . . . . . . . . . . . . . . . 77

14 Kernels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Introduction . . . . . . . . . . . . . . . . . . . . . . . . 79
14.1
14.2 Kernel functions . . . . . . . . . . . . . . . . . . . . 79
14.2.1 RBF kernels . . . . . . . . . . . . . . . . 79
14.2.2 TF-IDF kernels . . . . . . . . . . . . . 79
14.2.3 Mercer (positive deﬁnite)

kernels . . . . . . . . . . . . . . . . . . . . 79
14.2.4 Linear kernels . . . . . . . . . . . . . . 80
14.2.5 Matern kernels . . . . . . . . . . . . . . 80
String kernels . . . . . . . . . . . . . . . 80
14.2.6
14.2.7
Pyramid match kernels . . . . . . . 81
14.2.8 Kernels derived from

probabilistic generative models 81
14.3 Using kernels inside GLMs . . . . . . . . . . . 81
14.3.1 Kernel machines . . . . . . . . . . . . 81
14.3.2 L1VMs, RVMs, and other

sparse vector machines . . . . . . . 81
14.4 The kernel trick . . . . . . . . . . . . . . . . . . . . . 81
14.4.1 Kernelized KNN . . . . . . . . . . . . 82
14.4.2 Kernelized K-medoids

clustering . . . . . . . . . . . . . . . . . . 82
14.4.3 Kernelized ridge regression . . . 82
14.4.4 Kernel PCA . . . . . . . . . . . . . . . . 83
14.5 Support vector machines (SVMs) . . . . . . 83
SVMs for classiﬁcation . . . . . . . 83
14.5.1
SVMs for regression . . . . . . . . . 84
14.5.2
14.5.3 Choosing C . . . . . . . . . . . . . . . . 85
14.5.4 A probabilistic interpretation

of SVMs . . . . . . . . . . . . . . . . . . . 85
Summary of key points . . . . . . . 85

14.5.5

14.6 Comparison of discriminative kernel

methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
14.7 Kernels for building generative models . 86

15 Gaussian processes . . . . . . . . . . . . . . . . . . . . . . . 87
15.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . 87
15.2 GPs for regression . . . . . . . . . . . . . . . . . . 87
15.3 GPs meet GLMs . . . . . . . . . . . . . . . . . . . . 87
15.4 Connection with other methods . . . . . . . . 87
15.5 GP latent variable model . . . . . . . . . . . . . 87
15.6 Approximation methods for large

datasets . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

17 Hidden markov Model . . . . . . . . . . . . . . . . . . . . 91
17.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . 91
17.2 Markov models . . . . . . . . . . . . . . . . . . . . . 91

18 State space models . . . . . . . . . . . . . . . . . . . . . . . 93

19 Undirected graphical models (Markov

random ﬁelds) . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

20 Exact inference for graphical models . . . . . . . 97

21 Variational inference . . . . . . . . . . . . . . . . . . . . . 99

22 More variational inference . . . . . . . . . . . . . . . . 101

23 Monte Carlo inference . . . . . . . . . . . . . . . . . . . . 103

24 Markov chain Monte Carlo

(MCMC)inference . . . . . . . . . . . . . . . . . . . . . . . 105
24.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . 105
24.2 Metropolis Hastings algorithm . . . . . . . . 105
24.3 Gibbs sampling . . . . . . . . . . . . . . . . . . . . . 105
24.4 Speed and accuracy of MCMC . . . . . . . . 105
24.5 Auxiliary variable MCMC * . . . . . . . . . . 105

25 Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

26 Graphical model structure learning . . . . . . . . 109

27 Latent variable models for discrete data . . . . 111
Introduction . . . . . . . . . . . . . . . . . . . . . . . . 111
27.1
27.2 Distributed state LVMs for discrete data 111

28 Deep learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

A Optimization methods . . . . . . . . . . . . . . . . . . . . 115
A.1
Convexity . . . . . . . . . . . . . . . . . . . . . . . . . . 115
A.2 Gradient descent . . . . . . . . . . . . . . . . . . . . 115
Stochastic gradient descent
. . . 115
A.2.1
Batch gradient descent . . . . . . . 115
A.2.2
A.2.3
Line search . . . . . . . . . . . . . . . . . 115
A.2.4 Momentum term . . . . . . . . . . . . 116
Lagrange duality . . . . . . . . . . . . . . . . . . . . 116
Primal form . . . . . . . . . . . . . . . . 116
A.3.1
A.3.2 Dual form . . . . . . . . . . . . . . . . . . 116
A.4 Newton’s method . . . . . . . . . . . . . . . . . . . 116
A.5 Quasi-Newton method . . . . . . . . . . . . . . . 116
A.5.1 DFP . . . . . . . . . . . . . . . . . . . . . . . 116

A.3

Preface

ix

A.5.2
A.5.3

BFGS . . . . . . . . . . . . . . . . . . . . . 116
Broyden . . . . . . . . . . . . . . . . . . . 117

Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

List of Contributors

Wei Zhang
PhD candidate at the Institute of Software, Chinese Academy of Sciences (ISCAS), Beijing, P.R.CHINA, e-mail:
zh3feng@gmail.com, has written chapters of Naive Bayes and SVM.

Fei Pan
Master at Beijing University of Technology, Beijing, P.R.CHINA, e-mail: example@gmail.com, has written
chapters of KMeans, AdaBoost.

Yong Li
PhD candidate at the Institute of Automation of the Chinese Academy of Sciences (CASIA), Beijing, P.R.CHINA,
e-mail: liyong3forever@gmail.com, has written chapters of Logistic Regression.

Jiankou Li
PhD candidate at the Institute of Software, Chinese Academy of Sciences (ISCAS), Beijing, P.R.CHINA, e-mail:
lijiankoucoco@163.com, has written chapters of BayesNet.

xi

Notation

Introduction

It is very difﬁcult to come up with a single, consistent notation to cover the wide variety of data, models and algorithms
that we discuss. Furthermore, conventions difer between machine learning and statistics, and between different books
and papers. Nevertheless, we have tried to be as consistent as possible. Below we summarize most of the notation
used in this book, although individual sections may introduce new notation. Note also that the same symbol may have
different meanings depending on the context, although we try to avoid this where possible.

General math notation

Symbol

Meaning

⌊x⌋
⌈x⌉
x (cid:10) y
x ⊙ y
a ^ b
a _ b
:a
I(x)
¥
!
(cid:181)
jxj
jSj
n!
(cid:209)
(cid:209)2
≜
O((cid:1))
R
1 : n
(cid:25)
arg max

x

B(a; b)

B((cid:11))
)
(
n
k
d(x)
exp(x)
G(x)
Y(x)

Floor of x, i.e., round down to nearest integer
Ceiling of x, i.e., round up to nearest integer
Convolution of x and y
Hadamard (elementwise) product of x and y
logical AND
logical OR
logical NOT
Indicator function, I(x) = 1 if x is true, else I(x) = 0
Inﬁnity
Tends towards, e.g., n ! ¥
Proportional to, so y = ax can be written as y (cid:181) x
Absolute value
Size (cardinality) of a set
Factorial function
Vector of ﬁrst derivatives
Hessian matrix of second derivatives
Deﬁned as
Big-O: roughly means order of magnitude
The real numbers
Range (Matlab convention): 1 : n = 1; 2; :::; n
Approximately equal to

f (x) Argmax: the value x that maximizes f

Beta function, B(a; b) =

Multivariate beta function,

G(a)G(b)
G(a + b)
G(ak)

(cid:213)
k
G((cid:229)
k

ak)

n choose k , equal to n!=(k!(nk)!)
Dirac delta function,d(x) = ¥ if x = 0, else d(x) = 0
Exponential function ex
∫ ¥
0 ux(cid:0)1e(cid:0)udu
Gamma function, G(x) =
logG(x)

Digamma function,Psi(x) =

d
dx

xiii

xiv

Notation

X

A set from which values are drawn (e.g.,X = RD)

Linear algebra notation

We use boldface lower-case to denote vectors, such as x, and boldface upper-case to denote matrices, such as X. We
denote entries in a matrix by non-bold upper case letters, such as Xi j.

Vectors are assumed to be column vectors, unless noted otherwise. We use (x1; (cid:1) (cid:1) (cid:1) ; xD) to denote a column vector
created by stacking D scalars. If we write X = (x1; (cid:1) (cid:1) (cid:1) ; xn), where the left hand side is a matrix, we mean to stack
the xi along the columns, creating a matrix.

Symbol

Meaning

X ≻ 0
tr(X)
det(X)
jXj
X (cid:0)1
X †
X T
xT
diag(x)
diag(X)
I or I d
1 or 1d
0 or 0d

X is a positive deﬁnite matrix
Trace of a matrix
Determinant of matrix X
Determinant of matrix X
Inverse of a matrix
Pseudo-inverse of a matrix
Transpose of a matrix
Transpose of a vector
Diagonal matrix made from vector x
Diagonal vector extracted from matrix X
Identity matrix of size d (cid:2) d (ones on diagonal, zeros of)
Vector of ones (of length d)
Vector of zeros (of length d)

√

jjxjj = jjxjj

2 Euclidean or ℓ2 norm

d
(cid:229)
j=1

x2
j

(cid:12)
(cid:12)

(cid:12)
(cid:12)x j

ℓ1 norm

d
(cid:229)
j=1
j’th column of matrix
transpose of i’th row of matrix (a column vector)
Element (i; j) of matrix X
Tensor product of x and y

jjxjj
1

X :; j
X i;:
X i; j
x (cid:10) y

Probability notation

We denote random and ﬁxed scalars by lower case, random and ﬁxed vectors by bold lower case, and random and
ﬁxed matrices by bold upper case. Occasionally we use non-bold upper case to denote scalar random variables. Also,
we use p() for both discrete and continuous random variables

Symbol

Meaning

X;Y
P()
F()
p(x)
f (x)
F(x; y)
p(x; y)
f (x; y)

Random variable
Probability of a random event
Cumulative distribution function(CDF), also called distribution function
Probability mass function(PMF)
probability density function(PDF)
Joint CDF
Joint PMF
Joint PDF

Notation

xv

Conditional PMF, also called conditional probability
Conditional PDF
X is independent of Y
X is not independent of Y
X is conditionally independent of Y given Z
X is not conditionally independent of Y given Z
X is distributed according to distribution p
Parameters of a Beta or Dirichlet distribution
Covariance of X
Expected value of X
Expected value of X wrt distribution q

p(XjY )
fXjY (xjy)
X ? Y
X ̸? Y
X ? Y jZ
X ̸? Y jZ
X (cid:24) p
(cid:11)
cov[X]
E[X]
Eq[X]
H(X) or H(p) Entropy of distribution p(X)
I(X;Y )
KL(pjjq)
ℓ((cid:18))
L(q; a)
l
L
mode[X]
m
(cid:22)
F
ϕ
(cid:25)
r

Mutual information between X and Y
KL divergence from distribution p to q
Log-likelihood function
Loss function for taking action a when true state of nature is q
Precision (inverse variance) l = 1=s2
Precision matrix L = S(cid:0)1
Most probable value of X
Mean of a scalar distribution
Mean of a multivariate distribution
cdf of standard normal
pdf of standard normal
multinomial parameter vector, Stationary distribution of Markov chain
Correlation coefﬁcient

sigm(x)
s2
S
var[x]
n
Z

Sigmoid (logistic) function,

1
1 + e(cid:0)x

Variance
Covariance matrix
Variance of x
Degrees of freedom parameter
Normalization constant of a probability distribution

Machine learning/statistics notation

In general, we use upper case letters to denote constants, such as C; K; M; N; T , etc. We use lower case letters as dummy
indexes of the appropriate range, such as c = 1 : C to index classes, i = 1 : M to index data cases, j = 1 : N to index
input features, k = 1 : K to index states or clusters, t = 1 : T to index time, etc.

We use x to represent an observed data vector. In a supervised problem, we use y or y to represent the desired output

label. We use z to represent a hidden variable. Sometimes we also use q to represent a hidden discrete variable.

Symbol Meaning

C
D
N
Nc
R
D
Dtest
X
Y

Number of classes
Dimensionality of data vector (number of features)
Number of data cases
Number of examples of class c,Nc = (cid:229)N
Number of outputs (response variables)
Training data D = f(xi; yi)ji = 1 : Ng
Test data
Input space
Output space

I(yi = c)

i=1

xvi

Notation

K
k(x; y)
K
H
L
J((cid:18))
f (x)
P(yjx)
l
ϕ(x)
F
q()
Q((cid:18); (cid:18)old) Auxiliary function in EM
T
T (D)
T
(cid:18)
(cid:18)(s)
ˆ(cid:18)
ˆ(cid:18)MLE
ˆ(cid:18)MAP
¯(cid:18)
w
b
W
xi j
xi
X

Number of states or dimensions of a variable (often latent)
Kernel function
Kernel matrix
Hypothesis space
Loss function
Cost function
Decision function
TODO
Strength of ℓ2 or ℓ1regularizer
Basis function expansion of feature vector x
Basis function expansion of design matrix X
Approximate or proposal distribution

Length of a sequence
Test statistic for data
Transition matrix of Markov chain
Parameter vector
s’th sample of parameter vector
Estimate (usually MLE or MAP) of (cid:18)
Maximum likelihood estimate of (cid:18)
MAP estimate of (cid:18)
Estimate (usually posterior mean) of (cid:18)
Vector of regression weights (called (cid:12) in statistics)
intercept (called e in statistics)
Matrix of regression weights
Component (i.e., feature) j of data case i ,for i = 1 : N; j = 1 : D
Training case, i = 1 : N
Design matrix of size N (cid:2) D
(cid:229)N

Empirical mean ¯x =

i=1 xi

1
N

Future test case
Feature test case
Vector of all training labels y = (y1; :::; yN)
Latent component j for case i

¯x

˜x
x(cid:3)
y
zi j

Chapter 1
Introduction

1.1 Types of machine learning

{

Supervised learning

Unsupervised learning

8

>>>>>>>><
>>>>>>>>:

Classiﬁcation
Regression
8
>>><
Discovering clusters
Discovering latent factors
>>>:
Discovering graph structure
Matrix completion

1.2 Three elements of a machine learning

model

deﬁned. For training example (xi; yi), the loss of predict-
ing the value by is L(yi; by).

The following is some common loss functions:

1. 0-1 loss function

{

L(Y; f (X)) = I(Y; f (X)) =

1; Y = f (X)
0; Y ̸= f (X)

2. Quadratic loss function L(Y; f (X)) = (Y (cid:0) f (X))2
3. Absolute loss function L(Y; f (X)) = jY (cid:0) f (X)j
4. Logarithmic loss function

L(Y; P(Y jX)) = (cid:0) log P(Y jX)

Deﬁnition 1.2. The risk of function f is deﬁned as the ex-
pected loss of f :

∫

Model = Representation + Evaluation + Optimization1

Rexp( f ) = E [L (Y; f (X))] =

L (y; f (x)) P(x; y)dxdy

1.2.1 Representation

In supervised learning, a model must be represented as
a conditional probability distribution P(yjx)(usually we
call it classiﬁer) or a decision function f (x). The set of
classiﬁers(or decision functions) is called the hypothesis
space of the model. Choosing a representation for a model
is tantamount to choosing the hypothesis space that it can
possibly learn.

1.2.2 Evaluation

In the hypothesis space, an evaluation function (also
called objective function or risk function) is needed to
distinguish good classiﬁers(or decision functions) from
bad ones.

1.2.2.1 Loss function and risk function

Deﬁnition 1.1. In order to measure how well a function
ﬁts the training data, a loss function L : Y (cid:2)Y ! R (cid:21) 0 is

1 Domingos, P. A few useful things to know about machine learning.
Commun. ACM. 55(10):7887 (2012).

which is also called expected loss or risk function.

Deﬁnition 1.3. The risk function Rexp( f ) can be esti-
mated from the training data as

(1.1)

Remp( f ) =

1
N

N
(cid:229)
i=1

L (yi; f (xi))

(1.2)

which is also called empirical loss or empirical risk.

You can deﬁne your own loss function, but if you’re
a novice, you’re probably better off using one from the
literature. There are conditions that loss functions should
meet2:

1. They should approximate the actual loss you’re trying
to minimize. As was said in the other answer, the stan-
dard loss functions for classiﬁcation is zero-one-loss
(misclassiﬁcation rate) and the ones used for training
classiﬁers are approximations of that loss.

2. The loss function should work with your intended op-
timization algorithm. That’s why zero-one-loss is not
used directly: it doesn’t work with gradient-based opti-
mization methods since it doesn’t have a well-deﬁned
gradient (or even a subgradient, like the hinge loss for
SVMs has).
The main algorithm that optimizes the zero-one-loss
directly is the old perceptron algorithm(chapter §??).

2 http://t.cn/zTrDxLO

1

2

1.2.2.2 ERM and SRM

1.3.2.3 Optimization

Deﬁnition 1.4. ERM(Empirical risk minimization)

No training is needed.

min
f 2F

Remp( f ) = min
f 2F

1
N

N
(cid:229)
i=1

L (yi; f (xi))

(1.3)

Deﬁnition 1.5. Structural risk

Rsmp( f ) =

1
N

N
(cid:229)
i=1

L (yi; f (xi)) + lJ( f )

(1.4)

Deﬁnition 1.6. SRM(Structural risk minimization)

min
f 2F

Rsrm( f ) = min
f 2F

1
N

N
(cid:229)
i=1

L (yi; f (xi)) + lJ( f )

(1.5)

1.2.3 Optimization

Finally, we need a training algorithm(also called learn-
ing algorithm) to search among the classiﬁers in the the
hypothesis space for the highest-scoring one. The choice
of optimization technique is key to the efﬁciency of the
model.

1.3.3 Overﬁtting

1.3.4 Cross validation

Deﬁnition 1.7. Cross validation, sometimes called rota-
tion estimation, is a model validation technique for assess-
ing how the results of a statistical analysis will generalize
to an independent data set3.

Common types of cross-validation:

1. K-fold cross-validation. In k-fold cross-validation, the
original sample is randomly partitioned into k equal
size subsamples. Of the k subsamples, a single sub-
sample is retained as the validation data for testing the
model, and the remaining k 1 subsamples are used as
training data.

2. 2-fold cross-validation. Also, called simple cross-
validation or holdout method. This is the simplest
variation of k-fold cross-validation, k=2.

3. Leave-one-out cross-validation(LOOCV). k=M,

the

number of original samples.

1.3 Some basic concepts

1.3.1 Parametric vs non-parametric models

1.3.5 Model selection

When we have a variety of models of different complex-
ity (e.g., linear or logistic regression models with differ-
ent degree polynomials, or KNN classiﬁers with different
values ofK), how should we pick the right one? A natural
approach is to compute the misclassiﬁcation rate on the
training set for each method.

1.3.2 A simple non-parametric classiﬁer:

K-nearest neighbours

1.3.2.1 Representation

y = f (x) = arg min

c

(cid:229)
xi2Nk(x)

I(yi = c)

(1.6)

where Nk(x) is the set of k points that are closest to point
x.

Usually use k-d tree to accelerate the process of ﬁnd-

ing k nearest points.

1.3.2.2 Evaluation

No training is needed.

3

http://en.wikipedia.org/wiki/

Cross-validation_(statistics)

Chapter 2
Probability

2.1 Frequentists vs. Bayesians

2.2.1.1 CDF

what is probability?

One is called the frequentist interpretation. In this
view, probabilities represent
long run frequencies of
events. For example, the above statement means that, if
we ﬂip the coin many times, we expect it to land heads
about half the time.

The other interpretation is called the Bayesian inter-
pretation of probability. In this view, probability is used
to quantify our uncertainty about something; hence it is
fundamentally related to information rather than repeated
trials (Jaynes 2003). In the Bayesian view, the above state-
ment means we believe the coin is equally likely to land
heads or tails on the next toss

One big advantage of the Bayesian interpretation is
that it can be used to model our uncertainty about events
that do not have long term frequencies. For example, we
might want to compute the probability that the polar ice
cap will melt by 2020 CE. This event will happen zero
or one times, but cannot happen repeatedly. Nevertheless,
we ought to be able to quantify our uncertainty about this
event. To give another machine learning oriented exam-
ple, we might have observed a blip on our radar screen,
and want to compute the probability distribution over the
location of the corresponding target (be it a bird, plane,
or missile). In all these cases, the idea of repeated trials
does not make sense, but the Bayesian interpretation is
valid and indeed quite natural. We shall therefore adopt
the Bayesian interpretation in this book. Fortunately, the
basic rules of probability theory are the same, no matter
which interpretation is adopted.

2.2 A brief review of probability theory

2.2.1 Basic concepts

We denote a random event by deﬁning a random variable
X.

Descrete random variable: X can take on any value

from a ﬁnite or countably inﬁnite set.

Continuous random variable: the value of X is real-

valued.

{

F(x) ≜ P(X (cid:20) x) =

(cid:229)u(cid:20)x p(u)
∫
x
(cid:0)¥ f (u)du

, discrete
, continuous

(2.1)

2.2.1.2 PMF and PDF

For descrete random variable, We denote the probability
of the event that X = x by P(X = x), or just p(x) for
short. Here p(x) is called a probability mass function
or PMF.A probability mass function is a function that
gives the probability that a discrete random variable is ex-
actly equal to some value4. This satisﬁes the properties
0 (cid:20) p(x) (cid:20) 1 and (cid:229)x2X p(x) = 1.
continuous
variable,
∫
x
(cid:0)¥ f (u)du,

equation
For
F(x) =
the function f (x) is called a
probability density function or PDF. A probability
density function is a function that describes the rela-
tive likelihood for this random variable to take on a
given value5.This satisﬁes the properties f (x) (cid:21) 0 and
∫ ¥
(cid:0)¥ f (x)dx = 1.

the

in

2.2.2 Mutivariate random variables

2.2.2.1 Joint CDF

We denote joint CDF by F(x; y) ≜ P(X (cid:20) x \ Y (cid:20) y) =
P(X (cid:20) x;Y (cid:20) y).

F(x; y) ≜ P(X (cid:20) x;Y (cid:20) y) =

{

(cid:229)u(cid:20)x;v(cid:20)y p(u; v)
∫
x
(cid:0)¥

∫
y
(cid:0)¥ f (u; v)dudv

product rule:

Chain rule:

p(X;Y ) = P(XjY )P(Y )

(2.2)

(2.3)

4

http://en.wikipedia.org/wiki/Probability_

mass_function
5

http://en.wikipedia.org/wiki/Probability_

density_function

3

4

p(X1:N) = p(X1)p(X3jX2; X1):::p(XNjX1:N(cid:0)1)

(2.4)

2.2.4 Independence and conditional

independence

2.2.2.2 Marginal distribution

Marginal CDF:

FX (x) ≜ F(x; +¥) =
8
<

(cid:229)
xi(cid:20)x
∫
:
x
(cid:0)¥ fX (u)du =

+¥
P(X = xi) = (cid:229)
(cid:229)
xi(cid:20)x
j=1
∫
∫
+¥
x
(cid:0)¥ f (u; v)dudv
(cid:0)¥

P(X = xi;Y = y j)

FY (y) ≜ F(+¥; y) =
8
><

(cid:229)
y j(cid:20)y
>:
∫
y
(cid:0)¥ fY (v)dv =

+¥
(cid:229)y j(cid:20)y P(X = xi;Y = y j)
(cid:229)
p(Y = y j) =
i=1
∫
∫
+¥
y
(cid:0)¥ f (u; v)dudv
(cid:0)¥

(2.5)

(2.6)

Marginal PMF and PDF:
{

P(X = xi) = (cid:229)+¥
∫
+¥
(cid:0)¥ f (x; y)dy
fX (x) =

j=1 P(X = xi;Y = y j)

, descrete
, continuous

(2.7)

{

p(Y = y j) = (cid:229)+¥
∫
+¥
(cid:0)¥ f (x; y)dx
fY (y) =

i=1 P(X = xi;Y = y j)

, descrete
, continuous

We say X and Y are unconditionally independent or
marginally independent, denoted X ? Y ,
if we can
represent the joint as the product of the two marginals,
i.e.,

X ? Y = P(X;Y ) = P(X)P(Y )

(2.12)

We say X and Y are conditionally independent(CI)
given Z if the conditional joint can be written as a product
of conditional marginals:

X ? Y jZ = P(X;Y jZ) = P(XjZ)P(Y jZ)

(2.13)

2.2.5 Quantiles

Since the cdf F is a monotonically increasing function,
it has an inverse; let us denote this by F (cid:0)1. If F is the
cdf of X , then F (cid:0)1(a) is the value of xa such that
P(X (cid:20) xa) = a; this is called the a quantile of F. The
value F (cid:0)1(0:5) is the median of the distribution, with half
of the probability mass on the left, and half on the right.
The values F (cid:0)1(0:25) and F 1(0:75)are the lower and up-
per quartiles.

(2.8)

2.2.6 Mean and variance

2.2.2.3 Conditional distribution

Conditional PMF:

p(X = xijY = y j) =

p(X = xi;Y = y j)
p(Y = y j)

if p(Y ) > 0 (2.9)

The pmf p(XjY ) is called conditional probability.

Conditional PDF:

The most familiar property of a distribution is its mean,or
expected value, denoted by m. For discrete rvs, it is de-
ﬁned as E[X] ≜ (cid:229)x2X xp(x), and for continuous rvs, it is
∫
deﬁned as E[X] ≜
X xp(x)dx. If this integral is not ﬁnite,
the mean is not deﬁned (we will see some examples of
this later).

The variance is a measure of the spread of a distribu-

tion, denoted by s2. This is deﬁned as follows:

fXjY (xjy) =

f (x; y)
fY (y)

2.2.3 Bayes rule

(2.10)

var[X] = E[(X (cid:0) m)2]
∫

(2.14)

=

=

(x (cid:0) m)2 p(x)dx
∫

∫

∫

x2 p(x)dx + m2

p(x)dx (cid:0) 2m

xp(x)dx

= E[X 2] (cid:0) m2

(2.15)

p(Y = yjX = x) =

=

p(X = x;Y = y)
p(X = x)
p(X = xjY = y)p(Y = y)
(cid:229)y′ p(X = xjY = y′)p(Y = y′)

(2.11)

from which we derive the useful result

E[X 2] = s2 + m2

(2.16)

The standard deviation is deﬁned as

std[X] ≜

√

var[X]

(2.17)

written as X (cid:24) Mu(n; (cid:18)). The pmf is given by

This is useful since it has the same units as X itself.

2.3 Some common discrete distributions

where

p(x) ≜

(

n
x1 (cid:1) (cid:1) (cid:1) xk

)

K
(cid:213)
k=1

qxk
k

)

(

n
x1 (cid:1) (cid:1) (cid:1) xk

≜

n!
x1!x2! (cid:1) (cid:1) (cid:1) xK!

5

(2.21)

In this section, we review some commonly used paramet-
ric distributions deﬁned on discrete state spaces, both ﬁ-
nite and countably inﬁnite.

Bernoulli distribution is just a special case of a Bino-
mial distribution with n = 1, and so is multinoulli distri-
bution as to multinomial distribution. See Table 2.1 for a
summary.

2.3.1 The Bernoulli and binomial

distributions

Table 2.1: Summary of the multinomial and related
distributions.

Deﬁnition 2.1. Now suppose we toss a coin only once.
Let X 2 f0; 1g be a binary random variable, with probabil-
ity of success or heads of q. We say that X has a Bernoulli
distribution. This is written as X (cid:24) Ber(q), where the
pmf is deﬁned as

Ber(xjq) ≜ qI(x=1)(1 (cid:0) q)I(x=0)

(2.18)

Deﬁnition 2.2. Suppose we toss a coin n times. Let X 2
f0; 1; (cid:1) (cid:1) (cid:1) ; ng be the number of heads. If the probability of
heads is q, then we say X has a binomial distribution,
written as X (cid:24) Bin(n; q). The pmf is given by

Bin(kjn; q) ≜

(
n
k

)

qk(1 (cid:0) q)n(cid:0)k

(2.19)

2.3.2 The multinoulli and multinomial

distributions

can

distribution

the outcome of

Deﬁnition 2.3. The Bernoulli
be
the outcome of one coin tosses. To
used to model
model
let
x = (I(x = 1); (cid:1) (cid:1) (cid:1) ; I(x = K)) 2 f0; 1gK be a random
vector(this is called dummy encoding or one-hot en-
coding), then we say X has a multinoulli distribution(or
categorical distribution), written as X (cid:24) Cat(q). The
pmf is given by:

tossing a K-sided dice,

p(x) ≜

K
(cid:213)
k=1

qI(xk=1)
k

(2.20)

Deﬁnition 2.4. Suppose we toss a K-sided dice n times.
Let x = (x1; x2; (cid:1) (cid:1) (cid:1) ; xK) 2 f0; 1; (cid:1) (cid:1) (cid:1) ; ngK be a random vec-
tor, where x j is the number of times side j of the dice
occurs, then we say X has a multinomial distribution,

Name

K n X

Bernoulli
Binomial
Multinoulli
Multinomial -

1 1 x 2 f0; 1g
1 - x 2 f0; 1; (cid:1) (cid:1) (cid:1) ; ng
- 1 x 2 f0; 1gK; (cid:229)K

k=1 xk = 1

- x 2 f0; 1; (cid:1) (cid:1) (cid:1) ; ngK ; (cid:229)K

k=1 xk = n

2.3.3 The Poisson distribution

Deﬁnition 2.5. We say that X 2 f0; 1; 2; (cid:1) (cid:1) (cid:1) g has a Pois-
son distribution with parameter l > 0, written as X (cid:24)
Poi(l), if its pmf is

p(xjl) = e(cid:0)l lx
x!

(2.22)

The ﬁrst term is just the normalization constant, re-

quired to ensure the distribution sums to 1.

The Poisson distribution is often used as a model for
counts of rare events like radioactive decay and trafﬁc ac-
cidents.

2.3.4 The empirical distribution

The empirical distribution function6, or empirical cdf,
is the cumulative distribution function associated with the
empirical measure of the sample. Let D = fx1; x2; (cid:1) (cid:1) (cid:1) ; xNg
be a sample set, it is deﬁned as

Fn(x) ≜ 1
N

N
(cid:229)
i=1

I(xi (cid:20) x)

(2.23)

6

http://en.wikipedia.org/wiki/Empirical_

distribution_function

6

Table 2.2: Summary of Bernoulli, binomial multinoulli and multinomial distributions.

Name

Written as

X

p(x)(or p(x))

E[X] var[X]

Bernoulli

Binomial

X (cid:24) Ber(q)
X (cid:24) Bin(n; q) x 2 f0; 1; (cid:1) (cid:1) (cid:1) ; ng

x 2 f0; 1g

Multinoulli X (cid:24) Cat((cid:18))

x 2 f0; 1gK; (cid:229)K

k=1 xk = 1

Multinomial X (cid:24) Mu(n; (cid:18)) x 2 f0; 1; (cid:1) (cid:1) (cid:1) ; ngK ; (cid:229)K

k=1 xk = n

Poisson

X (cid:24) Poi(l)

x 2 f0; 1; 2; (cid:1) (cid:1) (cid:1) g

q(1 (cid:0) q)
nq nq(1 (cid:0) q)

)

qI(x=1)(1 (cid:0) q)I(x=0) q
(
n
qk(1 (cid:0) q)n(cid:0)k
k
K
(cid:213)
(
k=1

-

qI(x j =1)
j
)
n
x1 (cid:1) (cid:1) (cid:1) xk
e(cid:0)l lx
x!

K
(cid:213)
k=1

qx j
j

-

l

-

-

l

2.4 Some common continuous distributions

2.4.2 Student’s t-distribution

In this section we present some commonly used univariate
(one-dimensional) continuous probability distributions.

2.4.1 Gaussian (normal) distribution

Table 2.3: Summary of Gaussian distribution.

Written as

f (x)

E[X] mode var[X]

X (cid:24) N (m; s2)

1p

2ps

(cid:0) 1

2s2 (x(cid:0)m)2

e

m

m

s2

If X (cid:24) N(0; 1),we say X follows a standard normal

distribution.

The Gaussian distribution is the most widely used dis-

tribution in statistics. There are several reasons for this.

1. First, it has two parameters which are easy to interpret,
and which capture some of the most basic properties of
a distribution, namely its mean and variance.

2. Second,the central limit theorem (Section TODO) tells
us that sums of independent random variables have an
approximately Gaussian distribution, making it a good
choice for modeling residual errors or noise.

3. Third, the Gaussian distribution makes the least num-
ber of assumptions (has maximum entropy), subject to
the constraint of having a speciﬁed mean and variance,
as we show in Section TODO; this makes it a good de-
fault choice in many cases.

4. Finally, it has a simple mathematical form, which re-
sults in easy to implement, but often highly effective,
methods, as we will see.

See (Jaynes 2003, ch 7) for a more extensive discussion
of why Gaussians are so widely used.

Table 2.4: Summary of Student’s t-distribution.

Written as

X (cid:24) T (m; s2; n)

f (x)

[

1 +

1
n

(

x (cid:0) m
n

]

)
2

E[X] mode var[X]

m

m

ns2
n(cid:0) 2

G( n+1
2 )
p
npG( n
2 )

where G(x) is the gamma function:

G(x) ≜

∫ ¥

0

tx(cid:0)1e(cid:0)t dt

(2.24)

m is the mean, s2 > 0 is the scale parameter, and n > 0
is called the degrees of freedom. See Figure 2.1 for some
plots.

The variance is only deﬁned if n > 2. The mean is only

deﬁned if n > 1.

As an illustration of the robustness of the Student dis-
tribution, consider Figure 2.2. We see that the Gaussian
is affected a lot, whereas the Student distribution hardly
changes. This is because the Student has heavier tails, at
least for small n(see Figure 2.1).

If n = 1, this distribution is known as the Cauchy
or Lorentz distribution. This is notable for having such
heavy tails that the integral that deﬁnes the mean does not
converge.

To ensure ﬁnite variance, we require n > 2. It is com-
mon to use n = 4, which gives good performance in a
range of problems (Lange et al. 1989). For n ≫ 5, the
Student distribution rapidly approaches a Gaussian distri-
bution and loses its robustness properties.

7

(a)

(b)

Fig. 2.2: Illustration of the effect of outliers on ﬁtting
Gaussian, Student and Laplace distributions. (a) No
outliers (the Gaussian and Student curves are on top of
each other). (b) With outliers. We see that the Gaussian is
more affected by outliers than the Student and Laplace
distributions.

2.4.3 The Laplace distribution

Here m is a location parameter and b > 0 is a scale param-
eter. See Figure 2.1 for a plot.

Its robustness to outliers is illustrated in Figure 2.2. It
also put mores probability density at 0 than the Gaussian.
This property is a useful way to encourage sparsity in a
model, as we will see in Section TODO.

(a)

(b)

Fig. 2.1: (a) The pdfs for a N (0; 1), T (0; 1; 1) and

p

Lap(0; 1=
2). The mean is 0 and the variance is 1 for
both the Gaussian and Laplace. The mean and variance
of the Student is undeﬁned when n = 1.(b) Log of these
pdfs. Note that the Student distribution is not
log-concave for any parameter value, unlike the Laplace
distribution, which is always log-concave (and
log-convex...) Nevertheless, both are unimodal.

Table 2.5: Summary of Laplace distribution.

Written as

X (cid:24) Lap(m; b)

1
2b

f (x)
(

exp

(cid:0)

jx (cid:0) mj
b

E[X] mode var[X]

)

m

m

2b2

8

Table 2.6: Summary of gamma distribution

2.4.5 The beta distribution

X

Written as
X (cid:24) Ga(a; b) x 2 R+ ba
G(a)

f (x)

E[X] mode var[X]

xa(cid:0)1e(cid:0)xb

a
b

a (cid:0) 1
b

a
b2

2.4.4 The gamma distribution

Here a > 0 is called the shape parameter and b > 0 is
called the rate parameter. See Figure 2.3 for some plots.

Here B(a; b)is the beta function,

B(a; b) ≜

G(a)G(b)
G(a + b)

(2.25)

See Figure 2.4 for plots of some beta distributions. We
require a; b > 0 to ensure the distribution is integrable
(i.e., to ensure B(a; b) exists). If a = b = 1, we get the
uniform distirbution. If a and b are both less than 1, we
get a bimodal distribution with spikes at 0 and 1; if a and
b are both greater than 1, the distribution is unimodal.

(a)

(b)

Fig. 2.3: Some Ga(a; b = 1) distributions. If a (cid:20) 1, the
mode is at 0, otherwise it is > 0.As we increase the rate
b, we reduce the horizontal scale, thus squeezing
everything leftwards and upwards. (b) An empirical pdf
of some rainfall data, with a ﬁtted Gamma distribution
superimposed.

Fig. 2.4: Some beta distributions.

2.4.6 Pareto distribution

The Pareto distribution is used to model the distribu-
tion of quantities that exhibit long tails, also called heavy
tails.

As k ! ¥, the distribution approaches d(x (cid:0) m). See
Figure 2.5(a) for some plots. If we plot the distribution
on a log-log scale, it forms a straight line, of the form
log p(x) = a log x + c for some constants a and c. See Fig-
ure 2.5(b) for an illustration (this is known as a power
law).

Table 2.7: Summary of Beta distribution

9

Name

Written as

X

f (x)

E[X] mode

var[X]

Beta distribution X (cid:24) Beta(a; b) x 2 [0; 1]

1
B(a; b)

xa(cid:0)1(1 (cid:0) x)b(cid:0)1

a
a + b

a (cid:0) 1
a + b (cid:0) 2

ab
(a + b)2(a + b + 1)

Table 2.8: Summary of Pareto distribution

Name

Written as

X

f (x)

E[X]

mode

var[X]

Pareto distribution X (cid:24) Pareto(k; m) x (cid:21) m kmkx(cid:0)(k+1)I(x (cid:21) m)

km
k (cid:0) 1

if k > 1 m

m2k
(k (cid:0) 1)2(k (cid:0) 2)

if k > 2

(a)

(b)

Fig. 2.5: (a) The Pareto distribution Pareto(xjm; k) for
m = 1. (b) The pdf on a log-log scale.

2.5 Joint probability distributions

Given a multivariate random variable or random vec-
tor 7 X 2 RD, the joint probability distribution8 is a
probability distribution that gives the probability that each
of X1; X2; (cid:1) (cid:1) (cid:1) ; XD falls in any particular range or discrete
set of values speciﬁed for that variable. In the case of only
two random variables, this is called a bivariate distribu-
tion, but the concept generalizes to any number of random
variables, giving a multivariate distribution.

The joint probability distribution can be expressed ei-
ther in terms of a joint cumulative distribution function
or in terms of a joint probability density function (in the
case of continuous variables) or joint probability mass
function (in the case of discrete variables).

2.5.1 Covariance and correlation

Deﬁnition 2.6. The covariance between two rvs X and
Y measures the degree to which X and Y are (linearly)
related. Covariance is deﬁned as

cov[X;Y ] ≜ E [(X (cid:0) E[X])(Y (cid:0) E[Y ])]
= E[XY ] (cid:0) E[X]E[Y ]

(2.26)

Deﬁnition 2.7. If X is a D-dimensional random vector, its
covariance matrix is deﬁned to be the following symmet-
ric, positive deﬁnite matrix:

7

http://en.wikipedia.org/wiki/Multivariate_

random_variable
8

http://en.wikipedia.org/wiki/Joint_

probability_distribution

10

cov[X] ≜ E
0

[
(X (cid:0) E[X])(X (cid:0) E[X])T

]

B
B
B
@

=

var[X1]
Cov[X2; X1]
...

Cov[X1; X2] (cid:1) (cid:1) (cid:1) Cov[X1; XD]
(cid:1) (cid:1) (cid:1) Cov[X2; XD]
...
. . .
Cov[XD; X1] Cov[XD; X2] (cid:1) (cid:1) (cid:1)
var[XD]

var[X2]
...

C
C
C
A

(2.27)
1

(2.28)

S is symmetric). A diagonal covariance matrix has D pa-
rameters, and has 0s in the off-diagonal terms. A spherical
or isotropic covariance,S = s2I D, has one free parameter.

2.5.3 Multivariate Student’s t-distribution

Deﬁnition 2.8. The (Pearson) correlation coefﬁcient be-
tween X and Y is deﬁned as

A more robust alternative to the MVN is the multivariate
Student’s t-distribution, whose pdf is given by

corr[X;Y ] ≜ Cov[X;Y ]
√

var[X]; var[Y ]

(2.29)

A correlation matrix has the form

0

B
B
B
@

R ≜

corr[X1; X1] corr[X1; X2] (cid:1) (cid:1) (cid:1) corr[X1; XD]
corr[X2; X1] corr[X2; X2] (cid:1) (cid:1) (cid:1) corr[X2; XD]
...
corr[XD; X1] corr[XD; X2] (cid:1) (cid:1) (cid:1) corr[XD; XD]

. . .

...

...

1

C
C
C
A

(2.30)
The correlation coefﬁcient can viewed as a degree of

linearity between X and Y , see Figure 2.6.

Uncorrelated does not imply independent. For ex-
ample, let X (cid:24) U((cid:0)1; 1) and Y = X 2. Clearly Y is depen-
dent on X(in fact, Y is uniquely determined by X), yet one
can show that corr[X;Y ] = 0. Some striking examples of
this fact are shown in Figure 2.6. This shows several data
sets where there is clear dependence between X and Y , and
yet the correlation coefﬁcient is 0. A more general mea-
sure of dependence between random variables is mutual
information, see Section TODO.

2.5.2 Multivariate Gaussian distribution

The multivariate Gaussian or multivariate nor-
mal(MVN) is the most widely used joint probability
density function for continuous variables. We discuss
MVNs in detail in Chapter 4; here we just give some
deﬁnitions and plots.

The pdf of the MVN in D dimensions is deﬁned by the

following:

N (xj(cid:22); S) ≜

1
(2p)D=2jSj1=2

exp

[
(cid:0) 1
2

]
(x (cid:0) (cid:22))T S(cid:0)1(x (cid:0) (cid:22))

(2.31)
where (cid:22) = E[X] 2 RD is the mean vector, and S = Cov[X]
is the D (cid:2) D covariance matrix. The normalization con-
stant (2p)D=2jSj1=2 just ensures that the pdf integrates to
1.

Figure 2.7 plots some MVN densities in 2d for three
different kinds of covariance matrices. A full covariance
matrix has A D(D+1)=2 parameters (we divide by 2 since

T (xj(cid:22); S; n)
G( n+D
2 )
G( n
2 )

≜

jSj(cid:0) 1
2
D
2

(np)

[

1 +

1
n (x (cid:0) (cid:22))T S(cid:0)1 (x (cid:0) (cid:22))

](cid:0) n+D

2

(2.32)

=

G( n+D
2 )
G( n
2 )

jSj(cid:0) 1
2
D
2

(np)

[
1 + (x (cid:0) (cid:22))T V (cid:0)1 (x (cid:0) (cid:22))

](cid:0) n+D

2

(2.33)

where S is called the scale matrix (since it is not exactly
the covariance matrix) and V = nS. This has fatter tails
than a Gaussian. The smaller n is, the fatter the tails. As
n! ¥, the distribution tends towards a Gaussian. The dis-
tribution has the following properties

mean = (cid:22) , mode = (cid:22) , Cov =

n
n(cid:0) 2

S

(2.34)

2.5.4 Dirichlet distribution

A multivariate generalization of the beta distribution is the
Dirichlet distribution, which has support over the prob-
ability simplex, deﬁned by

{

SK =

x : 0 (cid:20) xk (cid:20) 1;

}

K
(cid:229)
k=1

xk = 1

(2.35)

The pdf is deﬁned as follows:

Dir(xj(cid:11)) ≜ 1
B((cid:11))

K
(cid:213)
k=1

ak(cid:0)1
k

x

I(x 2 SK)

(2.36)

where B(a1; a2; (cid:1) (cid:1) (cid:1) ; aK) is the natural generalization of
the beta function to K variables:

B(a) ≜

(cid:213)K

G(ak)

k=1
G(a0)

where a0 ≜

K
(cid:229)
k=1

ak

(2.37)

Figure 2.8 shows some plots of the Dirichlet when
K = 3, and Figure 2.9 for some sampled probability vec-
tors. We see that a0 controls the strength of the dis-

11

Fig. 2.6: Several sets of (x; y) points, with the Pearson correlation coefﬁcient of x and y for each set. Note that the
correlation reﬂects the noisiness and direction of a linear relationship (top row), but not the slope of that relationship
(middle), nor many aspects of nonlinear relationships (bottom). N.B.: the ﬁgure in the center has a slope of 0 but in
that case the correlation coefﬁcient is undeﬁned because the variance of Y is
zero.Source:http://en.wikipedia.org/wiki/Correlation

tribution (how peaked it is), and thekcontrol where the
peak occurs. For example, Dir(1; 1; 1) is a uniform dis-
tribution, Dir(2; 2; 2) is a broad distribution centered at
(1=3; 1=3; 1=3), and Dir(20; 20; 20) is a narrow distribu-
tion centered at (1=3; 1=3; 1=3).If ak < 1 for all k, we get
spikes at the corner of the simplex.

For future reference, the distribution has these proper-

ties

E(xk) =

ak
a0

, mode[xk] =

ak (cid:0) 1
a0 (cid:0) K

, var[xk] =

ak(a0 (cid:0) ak)
0 (a0 + 1)
a2
(2.38)

2.6 Transformations of random variables

If x (cid:24) P() is some random variable, and y = f (x), what
is the distribution of Y ? This is the question we address in
this section.

2.6.1 Linear transformations

Suppose g() is a linear function:

this is called the linearity of expectation.

For the covariance, we have

Cov[y] = Cov[Ax + b] = ASAT

(2.41)

2.6.2 General transformations

If X is a discrete rv, we can derive the pmf for y by simply
summing up the probability mass for all the xs such that
f (x) = y:

pY (y) = (cid:229)

pX (x)

(2.42)

x:g(x)=y

If X is continuous, we cannot use Equation 2.42 since
pX (x) is a density, not a pmf, and we cannot sum up den-
sities. Instead, we work with cdfs, and write
∫

FY (y) = P(Y (cid:20) y) = P(g(X) (cid:20) y) =

fX (x)dx

We can derive the pdf of Y by differentiating the cdf:

g(X)(cid:20)y

(2.43)

fY (y) = fX (x)j dx
dy

j

(2.44)

g(x) = Ax + b

(2.39)

First, for the mean, we have

E[y] = E[Ax + b] = AE[x] + b

(2.40)

This is called change of variables formula. We leave

the proof of this as an exercise.

For example, suppose X (cid:24) U(1; 1), and Y = X 2. Then

pY (y) =

y(cid:0) 1
2 .

1
2

12

(a)

(b)

(c)

(d)

Fig. 2.7: We show the level sets for 2d Gaussians. (a) A
full covariance matrix has elliptical contours.(b) A
diagonal covariance matrix is an axis aligned ellipse. (c)
A spherical covariance matrix has a circular shape. (d)
Surface plot for the spherical Gaussian in (c).

(a)

(b)

(c)

(d)

Fig. 2.8: (a) The Dirichlet distribution when K = 3
deﬁnes a distribution over the simplex, which can be
represented by the triangular surface. Points on this

surface satisfy 0 (cid:20) qk (cid:20) 1 and (cid:229)K
qk = 1. (b) Plot of the
Dirichlet density when (cid:11) = (2; 2; 2). (c) (cid:11) = (20; 2; 2).

k=1

2.6.3 Central limit theorem

13

Given N random variables X1; X2; (cid:1) (cid:1) (cid:1) ; XN, each variable is
independent and identically distributed9(iid for short),
and each has the same mean m and variance s2, then

n
(cid:229)
i=1

Xi (cid:0) Nm
p

Ns

(cid:24) N (0; 1)

(2.47)

(a) (cid:11) = (0:1; (cid:1) (cid:1) (cid:1) ; 0:1). This results in very sparse
distributions, with many 0s.

(b) (cid:11) = (1; (cid:1) (cid:1) (cid:1) ; 1). This results in more uniform (and
dense) distributions.

Fig. 2.9: Samples from a 5-dimensional symmetric
Dirichlet distribution for different parameter values.

2.6.2.1 Multivariate change of variables *

Let f be a function f : Rn ! Rn, and let y = f (x). Then
its Jacobian matrix J is given by

J x!y ≜

¶y
¶x

≜

1

C
C
A

0

B
B
@

¶y1
¶x1
...
¶yn
¶x1

(cid:1) (cid:1) (cid:1) ¶y1
¶xn
...
...
(cid:1) (cid:1) (cid:1) ¶yn
¶xn

(2.45)

jdet(J )j measures how much a unit cube changes in vol-
ume when we apply f .

If f is an invertible mapping, we can deﬁne the pdf of
the transformed variables using the Jacobian of the inverse
mapping y ! x:

py(y) = px(x)jdet(

¶x
¶y

)j = px(x)jdet(J y!x)j

(2.46)

this can also be written as

¯X (cid:0) m
p
s=
N

(cid:24) N (0; 1)

, where ¯X ≜ 1
N

n
(cid:229)
i=1

Xi

(2.48)

2.7 Monte Carlo approximation

In general, computing the distribution of a function of an
rv using the change of variables formula can be difﬁcult.
One simple but powerful alternative is as follows. First
we generate S samples from the distribution, call them
x1; (cid:1) (cid:1) (cid:1) ; xS. (There are many ways to generate such sam-
ples; one popular method, for high dimensional distribu-
tions, is called Markov chain Monte Carlo or MCMC;
this will be explained in Chapter TODO.) Given the sam-
ples, we can approximate the distribution of f (X) by us-
ing the empirical distribution of f f (xs)gS
s=1. This is called
a Monte Carlo approximation10, named after a city in
Europe known for its plush gambling casinos.

We can use Monte Carlo to approximate the expected
value of any function of a random variable. We simply
draw samples, and then compute the arithmetic mean of
the function applied to the samples. This can be written as
follows:

∫

E[g(X)] =

g(x)p(x)dx (cid:25) 1
S

S
(cid:229)
s=1

f (xs)

(2.49)

where xs (cid:24) p(X).

This is called Monte Carlo integration11, and has the
advantage over numerical integration (which is based on
evaluating the function at a ﬁxed grid of points) that the
function is only evaluated in places where there is non-
negligible probability.

9

http://en.wikipedia.org/wiki/Independent_

identically_distributed
10

http://en.wikipedia.org/wiki/Monte_Carlo_

method
11

http://en.wikipedia.org/wiki/Monte_Carlo_

integration

14

2.8 Information theory

2.8.1 Entropy

The entropy of a random variable X with distribution p,
denoted by H(X) or sometimes H(p), is a measure of its
uncertainty. In particular, for a discrete variable with K
states, it is deﬁned by

H(X) ≜ (cid:0)

K
(cid:229)
k=1

p(X = k) log2 p(X = k)

(2.50)

Usually we use log base 2, in which case the units are
called bits(short for binary digits). If we use log base e ,
the units are called nats.

The discrete distribution with maximum entropy is
the uniform distribution (see Section XXX for a proof).
Hence for a K-ary random variable, the entropy is maxi-
mized if p(x = k) = 1=K; in this case, H(X) = log2 K.

Conversely, the distribution with minimum entropy
(which is zero) is any delta-function that puts all its mass
on one state. Such a distribution has no uncertainty.

H(p; q) = (cid:229)
x

p(x) log2 q(x)

(2.53)

One can show (Cover and Thomas 2006) that the cross
entropy is the average number of bits needed to encode
data coming from a source with distribution p when we
use model q to deﬁne our codebook. Hence the regular
entropy H(p) = H(p; p), deﬁned in section §2.8.1,is the
expected number of bits if we use the true model, so the
KL divergence is the diference between these. In other
words, the KL divergence is the average number of extra
bits needed to encode the data, due to the fact that we
used distribution q to encode the data instead of the true
distribution p.

The extra number of bits interpretation should make it
clear that KL(pjjq) (cid:21) 0, and that the KL is only equal to
zero if q = p. We now give a proof of this important result.

Theorem 2.1. (Information inequality) KL(pjjq) (cid:21)
0 with equality iff p = q.

One important consequence of this result is that the
discrete distribution with the maximum entropy is the uni-
form distribution.

2.8.2 KL divergence

2.8.3 Mutual information

One way to measure the dissimilarity of two probability
distributions, p and q , is known as the Kullback-Leibler
divergence(KL divergence)or relative entropy. This is
deﬁned as follows:

KL(PjjQ) ≜ (cid:229)
x

p(x) log2

p(x)
q(x)

(2.51)

where the sum gets replaced by an integral for pdfs12. The
KL divergence is only deﬁned if P and Q both sum to 1
and if q(x) = 0 implies p(x) = 0 for all x(absolute con-
tinuity). If the quantity 0 ln 0 appears in the formula, it is
x ln x. We can rewrite this
interpreted as zero because lim
x!0
as

KL(pjjq) ≜ (cid:229)
x

p(x) log2 p(x) (cid:0)

K
(cid:229)
k=1

p(x) log2 q(x)

= H(p) (cid:0) H(p; q)

(2.52)

where H(p; q) is called the cross entropy,

12 The KL divergence is not a distance, since it is asymmet-
ric. One symmetric version of the KL divergence is the Jensen-
Shannon divergence, deﬁned as JS(p1; p2) = 0:5KL(p1jjq) +
0:5KL(p2jjq),where q = 0:5p1 + 0:5p2

Deﬁnition 2.9. Mutual information or MI, is deﬁned as
follows:

I(X;Y ) ≜ KL(P(X;Y )jjP(X)P(X))
p(x; y)
p(x)p(y)

p(x; y) log

= (cid:229)
x

(cid:229)
y

(2.54)

We have I(X;Y ) (cid:21) 0 with equality if P(X;Y ) =
P(X)P(Y ). That is, the MI is zero if the variables are
independent.

To gain insight into the meaning of MI, it helps to re-
express it in terms of joint and conditional entropies. One
can show that the above expression is equivalent to the
following:

I(X;Y ) = H(X) (cid:0) H(XjY )
= H(Y ) (cid:0) H(Y jX)
= H(X) + H(Y ) (cid:0) H(X;Y )
= H(X;Y ) (cid:0) H(XjY ) (cid:0) H(Y jX)

(2.55)
(2.56)

(2.57)
(2.58)

where H(X) and H(Y ) are the marginal entropies,
H(XjY ) and H(Y jX) are the conditional entropies, and
H(X;Y ) is the joint entropy of X and Y , see Fig. 2.1013.

13

http://en.wikipedia.org/wiki/Mutual_

information

15

Fig. 2.10: Individual H(X); H(Y ), joint H(X;Y ), and
conditional entropies for a pair of correlated subsystems
X;Y with mutual information I(X;Y ).

Intuitively, we can interpret the MI between X and Y as
the reduction in uncertainty about X after observing Y , or,
by symmetry, the reduction in uncertainty about Y after
observing X.

A quantity which is closely related to MI is the point-
wise mutual information or PMI. For two events (not
random variables) x and y, this is deﬁned as

PMI(x; y) ≜ log

p(x; y)
p(x)p(y)

= log

p(xjy)
p(x)

= log

p(yjx)
p(y)

(2.59)
This measures the discrepancy between these events
occuring together compared to what would be expected
by chance. Clearly the MI of X and Y is just the expected
value of the PMI. Interestingly, we can rewrite the PMI as
follows:

PMI(x; y) = log

p(xjy)
p(x)

= log

p(yjx)
p(y)

(2.60)

This is the amount we learn from updating the prior
p(x) into the posterior p(xjy) , or equivalently, updating
the prior p(y) into the posterior p(yjx) .

Chapter 3
Generative models for discrete data

3.1 Generative classiﬁer

p(y = cjx; (cid:18)) =

p(y = cj(cid:18))p(xjy = c; (cid:18))
(cid:229)c′ p(y = c′j(cid:18))p(xjy = c′; (cid:18))

(3.1)

This is called a generative classiﬁer, since it speciﬁes
how to generate the data using the class conditional den-
sity p(xjy = c) and the class prior p(y = c). An alternative
approach is to directly ﬁt the class posterior, p(y = cjx)
;this is known as a discriminative classiﬁer.

ferent answers. In fact, they presumably not only have dif-
ferent priors, but also different hypothesis spaces. How-
ever, we can ﬁnesse that by deﬁning the hypothesis space
of the child and the math professor to be the same, and
then setting the childs prior weight to be zero on certain
advanced concepts. Thus there is no sharp distinction be-
tween the prior and the hypothesis space.

However, the prior is the mechanism by which back-
ground knowledge can be brought to bear on a prob-
lem. Without this, rapid learning (i.e., from small samples
sizes) is impossible.

3.2 Bayesian concept learning

Psychological research has shown that people can learn
concepts from positive examples alone (Xu and Tenen-
baum 2007).

We can think of learning the meaning of a word as
equivalent to concept learning, which in turn is equiv-
alent to binary classiﬁcation. To see this, deﬁne f (x) = 1
if xis an example of the concept C, and f (x) = 0 other-
wise. Then the goal is to learn the indicator function f ,
which just deﬁnes which elements are in the set C.

3.2.3 Posterior

The posterior is simply the likelihood times the prior, nor-
malized.

p(hjD) ≜

p(Djh)p(h)
(cid:229)h′2H p(Djh′)p(h′)

I(D 2 h)p(h)
(cid:229)h′2H I(D 2 h′)p(h′)
(3.3)
where I(D 2 h)p(h) is 1 iff(iff and only if) all the data are
in the extension of the hypothesis h.

=

3.2.1 Likelihood

p(Djh) ≜

(

1
size(h)

)
N

)
N

(

=

1
jhj

In general, when we have enough data, the posterior
p(hjD) becomes peaked on a single concept, namely the
MAP estimate, i.e.,

p(hjD) ! ˆhMAP

(3.4)

(3.2)

where ˆhMAP is the posterior mode,

This crucial equation embodies what Tenenbaum calls
the size principle, which means the model favours the
simplest (smallest) hypothesis consistent with the data.
This is more commonly known as Occams razor14.

3.2.2 Prior

The prior is decided by human, not machines, so it is sub-
jective. The subjectivity of the prior is controversial. For
example, that a child and a math professor will reach dif-

14

razor

http://en.wikipedia.org/wiki/Occam%27s_

ˆhMAP ≜ arg max

h

p(hjD) = arg max

h

p(Djh)p(h)

= arg max

h

[log p(Djh) + log p(h)]

(3.5)

Since the likelihood term depends exponentially on N,
and the prior stays constant, as we get more and more data,
the MAP estimate converges towards the maximum like-
lihood estimate or MLE:

ˆhMLE ≜ arg max

h

p(Djh) = arg max

h

log p(Djh)

(3.6)

In other words, if we have enough data, we see that the

data overwhelms the prior.

17

18

3.2.4 Posterior predictive distribution

p(qjDa; Db) = p(q; DbjDa)p(Da)

The concept of posterior predictive distribution15 is
normally used in a Bayesian context, where it makes use
of the entire posterior distribution of the parameters given
the observed data to yield a probability distribution over
an interval rather than simply a point estimate.

p( ˜xjD) ≜ EhjD[p( ˜xjh)] =

{

(cid:229)h p( ˜xjh)p(hjD)
∫
p( ˜xjh)p(hjD)dh

(3.7)

This is just a weighted average of the predictions of
each individual hypothesis and is called Bayes model av-
eraging(Hoeting et al. 1999).

3.3 The beta-binomial model

3.3.1 Likelihood

Given X (cid:24) Bin(q), the likelihood of D is given by

p(Djq) = Bin(N1jN; q)

(3.8)

3.3.2 Prior

Beta(qja; b) (cid:181) qa(cid:0)1(1 (cid:0) q)b(cid:0)1

(3.9)

The parameters of

the prior are called hyper-

parameters.

3.3.3 Posterior

p(qjD) (cid:181) Bin(N1jN1 + N0; q)Beta(qja; b)
= Beta(qjN1 + a; N0b)

(3.10)

Note that updating the posterior sequentially is equiv-
alent to updating in a single batch. To see this, suppose
we have two data sets Da and Db with sufﬁcient statistics
Na
1 ; Na
0 be
the sufﬁcient statistics of the combined datasets. In batch
mode we have

0 . Let N1 = Na

1 and N0 = Na

0 and Nb

1 +Nb

0 +Nb

1 ; Nb

(cid:181) p(q; DbjDa)
= p(Db; qjDa)
= p(Dbjq)p(qjDa)
Combine Equation 3.10 and 2.19
= Bin(Nb
0 )Beta(qjNa
1
0 + Nb
= Beta(qjNa

1 + a; Na

1 + Nb

1 + Nb

jq; Nb

0 + b)

1 + a; Na
0 + b)

This makes Bayesian inference particularly well-suited

to online learning, as we will see later.

3.3.3.1 Posterior mean and mode

From Table 2.7, the posterior mean is given by

¯q =

a + N1
a + b + N

The mode is given by

ˆqMAP =

a + N1 (cid:0) 1
a + b + N (cid:0) 2

(3.11)

(3.12)

If we use a uniform prior, then the MAP estimate re-

duces to the MLE,

ˆqMLE =

N1
N

(3.13)

We will now show that the posterior mean is convex
combination of the prior mean and the MLE, which cap-
tures the notion that the posterior is a compromise be-
tween what we previously believed and what the data is
telling us.

3.3.3.2 Posterior variance

The mean and mode are point estimates, but it is useful to
know how much we can trust them. The variance of the
posterior is one way to measure this. The variance of the
Beta posterior is given by

var(qjD) =

(a + N1)(b + N0)
(a + N1 + b + N0)2(a + N1 + b + N0 + 1)

(3.14)
We can simplify this formidable expression in the case

that N ≫ a; b, to get

15

http://en.wikipedia.org/wiki/Posterior_

predictive_distribution

var(qjD) (cid:25) N1N0
NNN

=

ˆqMLE (1 (cid:0) ˆqMLE )
N

(3.15)

3.3.4 Posterior predictive distribution

Bb(xja; b; M) ≜

)

(

M
x

B(x + a; M (cid:0) x + b)
B(a; b)

19

(3.21)

So far, we have been focusing on inference of the un-
known parameter(s). Let us now turn our attention to pre-
diction of future observable data.

Consider predicting the probability of heads in a single

This distribution has the following mean and variance

mean = M

a
a + b

, var =

Mab
(a + b)2

a + b + M
a + b + 1

(3.22)

future trial under a Beta(a; b)posterior. We have
∫

p( ˜xjD) =

=

1

0
∫

1

0

p( ˜xjq)p(qjD)dq

qBeta(qja; b)dq

= E[qjD] =

a
a + b

(3.16)

This process is illustrated in Figure 3.1. We start with
a Beta(2; 2) prior, and plot the posterior predictive density
after seeing N1 = 3 heads and N0 = 17 tails. Figure 3.1(b)
plots a plug-in approximation using a MAP estimate. We
see that the Bayesian prediction has longer tails, spread-
ing its probability mass more widely, and is therefore less
prone to overﬁtting and blackswan type paradoxes.

3.3.4.1 Overﬁtting and the black swan paradox

Let us now derive a simple Bayesian solution to the prob-
lem. We will use a uniform prior, so a = b = 1. In this
case, plugging in the posterior mean gives Laplaces rule
of succession

p( ˜xjD) =

N1 + 1
N0 + N1 + 1

(3.17)

This justiﬁes the common practice of adding 1 to the
empirical counts, normalizing and then plugging them in,
a technique known as add-one smoothing. (Note that
plugging in the MAP parameters would not have this
smoothing effect, since the mode becomes the MLE if
a = b = 1, see Section 3.3.3.1.)

3.3.4.2 Predicting the outcome of multiple future

trials

Suppose now we were interested in predicting the number
of heads, ˜x, in M future trials. This is given by

p( ˜xjD) =

=

∫

1

0
(
M
˜x

Bin( ˜xjM; q)Beta(qja; b)dq
)

(3.18)

q˜x(1 (cid:0) q)M(cid:0) ˜xqa(cid:0)1(1 (cid:0) q)b(cid:0)1dq

1
B(a; b)

∫

1

0

(a)

(b)

(3.19)

Fig. 3.1: (a) Posterior predictive distributions after seeing
N1 = 3; N0 = 17. (b) MAP estimation.

We recognize the integral as the normalization constant

for a Beta(a + ˜x; M ˜x + b) distribution. Hence
∫

1

0

q˜x(1(cid:0)q)M(cid:0) ˜xqa(cid:0)1(1(cid:0)q)b(cid:0)1dq = B( ˜x+a; M (cid:0) ˜x+b)
(3.20)
Thus we ﬁnd that the posterior predictive is given by
the following, known as the (compound) beta-binomial
distribution:

3.4 The Dirichlet-multinomial model

In the previous section, we discussed how to infer the
probability that a coin comes up heads. In this section,

20

we generalize these results to infer the probability that a
dice with K sides comes up as face k.

p(X = jjD) =

=

p(X = jj(cid:18))p((cid:18)jD)d(cid:18)

[∫

(3.30)
]

p(X = jjqj)

p((cid:18)(cid:0) j; qjjD)d(cid:18)(cid:0) j

dqj

∫

∫

∫

3.4.1 Likelihood

Suppose we observe N dice rolls, D = fx1; x2; (cid:1) (cid:1) (cid:1) ; xNg,
where xi 2 f1; 2; (cid:1) (cid:1) (cid:1) ; Kg. The likelihood has the form

p(Dj(cid:18)) =

(

N
N1 (cid:1) (cid:1) (cid:1) Nk

)

K
(cid:213)
k=1

qNk
k

where Nk =

N
(cid:229)
i=1

I(yi = k)

(3.23)

almost the same as Equation 2.21.

3.4.2 Prior

Dir((cid:18)j(cid:11)) =

1
B((cid:11))

K
(cid:213)
k=1

qak(cid:0)1
k

I((cid:18) 2 SK)

(3.24)

3.4.3 Posterior

p((cid:18)jD) (cid:181) p(Dj(cid:18))p((cid:18))
K
(cid:213)
k=1

qak(cid:0)1
k

qNk
k

(cid:181)

=

K
(cid:213)
k=1

qNk+ak(cid:0)1
k

= Dir((cid:18)ja1 + N1; (cid:1) (cid:1) (cid:1) ; aK + NK)

(3.26)

(3.27)

From Equation 2.38, the MAP estimate is given by

Nk + ak (cid:0) 1
N + a0 (cid:0) K
If we use a uniform prior, ak = 1, we recover the MLE:

ˆqk =

(3.28)

ˆqk =

Nk
N

(3.29)

3.4.4 Posterior predictive distribution

The posterior predictive distribution for a single multi-
noulli trial is given by the following expression:

=

qj p(qjjD)dqj = E[qjjD] =

(3.31)

aj + N j
a0 + N

(3.32)

where (cid:18)(cid:0) j are all the components of (cid:18) except qj.

The above expression avoids the zero-count problem.
In fact, this form of Bayesian smoothing is even more im-
portant in the multinomial case than the binary case, since
the likelihood of data sparsity increases once we start par-
titioning the data into many categories.

3.5 Naive Bayes classiﬁers

Assume the features are conditionally independent given
the class label, then the class conditional density has the
following form

p(xjy = c; (cid:18)) =

D
(cid:213)
j=1

p(x jjy = c; (cid:18) jc)

(3.33)

ﬁer(NBC).

The form of the class-conditional density depends on
the type of each feature. We give some possibilities below:

•

•

•

j=1

jc), where mjc

real-valued features, we

can
p(xjy; (cid:18)) =
the mean of

case of
the Gaussian
N (x jjmjc; s2

In the
distribution:
use
(cid:213)D
is
feature j in objects of class c, and s2
jc is its variance.
In the case of binary features, x j 2 f0; 1g, we
can use the Bernoulli distribution: p(xjy; (cid:18)) =
j=1 Ber(x jjmjc), where mjc is the probability that
(cid:213)D
feature j occurs in class c. This is sometimes called
the multivariate Bernoulli naive Bayes model. We
will see an application of this below.
x j 2
features,
of
In
fa j1; a j2; (cid:1) (cid:1) (cid:1) ; a jS j
g, we
can use
the multinoulli
distribution: p(xjy; (cid:18)) = (cid:213)D
j=1 Cat(x jj(cid:22) jc), where (cid:22) jc
is a histogram over the K possible values for x j in
class c.

categorical

case

the

Obviously we can handle other kinds of features, or
use different distributional assumptions. Also, it is easy to
mix and match features of different types.

(3.25)

The resulting model is called a naive Bayes classi-

3.5.1 Optimization

3.5.1.2 Bayesian naive Bayes

We now discuss how to train a naive Bayes classiﬁer. This
usually means computing the MLE or the MAP estimate
for the parameters. However, we will also discuss how to
compute the full posterior, p((cid:18)jD).

Use a Dir((cid:11)) prior for (cid:25).

In the case of binary features, use a Beta(b0; b1) prior
for each qjc; in the case of categorical features, use a
Dir((cid:11)) prior for each (cid:18) jc. Often we just take (cid:11) = 1 and
(cid:12) = 1, corresponding to add-one or Laplace smoothing.

21

3.5.1.1 MLE for NBC

The probability for a single data case is given by

3.5.2 Using the model for prediction

p(xi; yij(cid:18)) = p(yij(cid:25))(cid:213)

p(xi jj(cid:18) j)

The goal is to compute

j
pI(yi=c)
c (cid:213)

j

(cid:213)
c

= (cid:213)
c

p(xi jj(cid:18) jc)I(yi=c)

(3.34)

y = f (x) = arg max

c

P(y = cjx; (cid:18))

Hence the log-likelihood is given by

p(Dj(cid:18)) =

C
(cid:229)
c=1

Nc log pc +

D
(cid:229)
j=1

C
(cid:229)
c=1

(cid:229)
i:yi=c

log p(xi jj(cid:18) jc)

(3.35)
I(yi = c) is the number of feature vectors in

where Nc ≜ (cid:229)
i
class c.

We see that this expression decomposes into a series
of terms, one concerning (cid:25), and DC terms containing the
qjcs. Hence we can optimize all these parameters sepa-
rately.

From Equation 3.29, the MLE for the class prior is

given by

Nc
N
The MLE for qjcs depends on the type of distribution

ˆpc =

(3.36)

we choose to use for each feature.

In the case of binary features, x j 2 f0; 1g, x jjy = c (cid:24)

Ber(qjc), hence

ˆqjc =

N jc
Nc

(3.37)

= P(y = cj(cid:18))

D
(cid:213)
j=1

P(x jjy = c; (cid:18))

(3.39)

We can the estimate parameters using MLE or MAP,
then the posterior predictive density is obtained by simply
plugging in the parameters ¯(cid:18)(MLE) or ˆ(cid:18)(MAP).

Or we can use BMA, just integrate out the unknown

parameters.

3.5.3 The log-sum-exp trick

when using generative classiﬁers of any kind, comput-
ing the posterior over class labels using Equation 3.1 can
fail due to numerical underﬂow. The problem is that
p(xjy = c) is often a very small number, especially if x
is a high-dimensional vector. This is because we require
that (cid:229)x p(xjy) = 1, so the probability of observing any
particular high-dimensional vector is small. The obvious
solution is to take logs when applying Bayes rule, as fol-
lows:

(

)

where N jc ≜ (cid:229)
i:yi=c

occurs in class c.
case
the
fa j1; a j2; (cid:1) (cid:1) (cid:1) ; a jS j

In

I(yi = c) is the number that feature j

log p(y = cjx; (cid:18)) = bc (cid:0) log

ebc′

(cid:229)
c′

(3.40)

of

categorical
g, x jjy = c (cid:24) Cat((cid:18) jc), hence

features,

x j 2

where bc ≜ log p(xjy = c; (cid:18)) + log p(y = cj(cid:18)).

ˆ(cid:18) jc = (

N j1c
Nc

;

N j2c
Nc

; (cid:1) (cid:1) (cid:1) ;

N jS j
Nc

)T

(3.38)

N
where N jkc ≜
(cid:229)
i=1
ture x j = a jk occurs in class c.

I(xi j = a jk; yi = c) is the number that fea-

We can factor out the largest term, and just represent

the remaining numbers relative to that. For example,

log(e(cid:0)120 + e(cid:0)121) = log(e(cid:0)120(1 + e(cid:0)1))
= log(1 + e(cid:0)1) (cid:0) 120

(3.41)

In general, we have

[

((cid:229) ebc(cid:0)B)eB

]

(

= log

(cid:229) ebc(cid:0)B

)

+B (3.42)

ebc = log

(cid:229)
c

22

where B ≜ maxfbcg.

This is called the log-sum-exp trick, and is widely

used.

p(xijyi = c; (cid:18)) =

=

D
(cid:213)
j=1

D
(cid:213)
j=1

Ber(xi jjqjc)

qxi j
jc (1 (cid:0) qjc)1(cid:0)xi j

(3.45)

3.5.4 Feature selection using mutual

This is called the Bernoulli product model, or the bi-

information

nary independence model.

Since an NBC is ﬁtting a joint distribution over potentially
many features, it can suffer from overﬁtting. In addition,
the run-time cost is O(D), which may be too high for some
applications.

One common approach to tackling both of these prob-
lems is to perform feature selection, to remove irrelevant
features that do not help much with the classiﬁcation prob-
lem. The simplest approach to feature selection is to eval-
uate the relevance of each feature separately, and then take
the top K,whereKis chosen based on some tradeoff be-
tween accuracy and complexity. This approach is known
as variable ranking, ﬁltering, or screening.

One way to measure relevance is to use mutual infor-
mation (Section 2.8.3) between feature X j and the class
label Y

I(X j;Y ) = (cid:229)
x j

(cid:229)
y

p(x j; y) log

p(x j; y)
p(x j)p(y)

(3.43)

If the features are binary, it is easy to show that the MI

can be computed as follows

[
qjcpc log

qjc
qj

I j = (cid:229)

c

+ (1 (cid:0) qjc)pc log

]

1 (cid:0) qjc
1 (cid:0) qj

(3.44)

where pc = p(y = c), qjc = p(x j = 1jy = c), and qj =
p(x j = 1) = (cid:229)c pcqjc.

3.5.5 Classifying documents using bag of

words

Document classiﬁcation is the problem of classifying
text documents into different categories.

3.5.5.1 Bernoulli product model

One simple approach is to represent each document as a
binary vector, which records whether each word is present
or not, so xi j = 1 iff word j occurs in document i, other-
wise xi j = 0. We can then use the following class condi-
tional density:

3.5.5.2 Multinomial document classiﬁer

However, ignoring the number of times each word oc-
curs in a document loses some information (McCallum
and Nigam 1998). A more accurate representation counts
the number of occurrences of each word. Speciﬁcally,
let xi be a vector of counts for document i, so xi j 2
f0; 1; (cid:1) (cid:1) (cid:1) ; Nig, where Ni is the number of terms in docu-

ment i(so

D
(cid:229)
j=1

xi j = Ni). For the class conditional densities,

we can use a multinomial distribution:

p(xijyi = c; (cid:18)) = Mu(xijNi; (cid:18)c) =

Ni!
j=1 xi j!

(cid:213)D

D
(cid:213)
j=1

qxi j
jc

(3.46)
where we have implicitly assumed that the document
length Ni is independent of the class. Here jc is the proba-
bility of generating word j in documents of class c; these
qjc = 1 for
parameters satisfy the constraint that (cid:229)D
each class c.

j=1

Although the multinomial classiﬁer is easy to train and
easy to use at test time, it does not work particularly well
for document classiﬁcation. One reason for this is that it
does not take into account the burstiness of word usage.
This refers to the phenomenon that most words never ap-
pear in any given document, but if they do appear once,
they are likely to appear more than once, i.e., words occur
in bursts.

The multinomial model cannot capture the burstiness
phenomenon. To see why, note that Equation 3.46 has the
form qxi j
jc , and since qjc ≪ 1 for rare words, it becomes
increasingly unlikely to generate many of them. For more
frequent words, the decay rate is not as fast. To see why
intuitively, note that the most frequent words are func-
tion words which are not speciﬁc to the class, such as
and, the, and but; the chance of the word and occuring
is pretty much the same no matter how many time it has
previously occurred (modulo document length), so the in-
dependence assumption is more reasonable for common
words. However, since rare words are the ones that mat-
ter most for classiﬁcation purposes, these are the ones we
want to model the most carefully.

23

3.5.5.3 DCM model

Various ad hoc heuristics have been proposed to improve
the performance of the multinomial document classiﬁer
(Rennie et al. 2003). We now present an alternative class
conditional density that performs as well as these ad hoc
methods, yet is probabilistically sound (Madsen et al.
2005).

Suppose we simply replace the multinomial class con-
ditional density with the Dirichlet Compound Multino-
mial or DCM density, deﬁned as follows:
∫

p(xijyi = c; (cid:11)) =

Mu(xijNi; (cid:18)c)Dir((cid:18)cj(cid:11)c)

=

Ni!
j=1 xi j!

(cid:213)D

D
(cid:213)
j=1

B(xi + (cid:11)c)
B((cid:11)c)

(3.47)

(This equation is derived in Equation TODO.) Surpris-
ingly this simple change is all that is needed to capture the
burstiness phenomenon. The intuitive reason for this is as
follows: After seeing one occurence of a word, say wordj,
the posterior counts on j gets updated, making another oc-
curence of wordjmore likely. By contrast, ifj is ﬁxed, then
the occurences of each word are independent. The multi-
nomial model corresponds to drawing a ball from an urn
with Kcolors of ball, recording its color, and then replac-
ing it. By contrast, the DCM model corresponds to draw-
ing a ball, recording its color, and then replacing it with
one additional copy; this is called the Polya urn.

Using the DCM as the class conditional density gives
much better results than using the multinomial, and has
performance comparable to state of the art methods, as de-
scribed in (Madsen et al. 2005). The only disadvantage is
that ﬁtting the DCM model is more complex; see (Minka
2000e; Elkan 2006) for the details.

Chapter 4
Gaussian Models

In this chapter, we discuss the multivariate Gaus-
sian or multivariate normal(MVN), which is the most
widely used joint probability density function for contin-
uous variables. It will form the basis for many of the mod-
els we will encounter in later chapters.

4.1 Basics

Recall from Section 2.5.2 that the pdf for an MVN in D
dimensions is deﬁned by the following:

N (xj(cid:22); S) ≜

1
D
2 jSj 1
2

exp

(2p)

[
(cid:0) 1
2

]
(x (cid:0) (cid:22))T S(cid:0)1(x (cid:0) (cid:22))

(4.1)
The expression inside the exponent is the Mahalanobis
distance between a data vector x and the mean vector (cid:22),
We can gain a better understanding of this quantity by per-
forming an eigendecomposition of (cid:6). That is, we write
(cid:6) = U (cid:3)U T , where U is an orthonormal matrix of eigen-
vectors satsifying U T U = I, and (cid:3) is a diagonal matrix
of eigenvalues. Using the eigendecomposition, we have
that

(cid:6)(cid:0)1 = U (cid:0)T (cid:3)(cid:0)1U (cid:0)1 = U (cid:3)(cid:0)1U T =

D
(cid:229)
i=1

1
li

uiuT
i

(4.2)

where ui is the i’th column of U , containing the i’th
eigenvector. Hence we can rewrite the Mahalanobis dis-
tance as follows:

(

)

(x (cid:0) (cid:22))T S(cid:0)1(x (cid:0) (cid:22)) = (x (cid:0) (cid:22))T

D
(cid:229)
i=1

1
li

uiuT
i

(x (cid:0) (cid:22))

+

= 1

y2
1
l1

y2
2
l2
Hence we see that the contours of equal probability
density of a Gaussian lie along ellipses. This is illustrated
in Figure 4.1. The eigenvectors determine the orientation
of the ellipse, and the eigenvalues determine how elogo-
nated it is.

(4.6)

Fig. 4.1: Visualization of a 2 dimensional Gaussian
density. The major and minor axes of the ellipse are
deﬁned by the ﬁrst two eigenvectors of the covariance
matrix, namely u1 and u2. Based on Figure 2.7 of
(Bishop 2006a)

In general, we see that the Mahalanobis distance corre-
sponds to Euclidean distance in a transformed coordinate
system, where we shift by (cid:22) and rotate by U .

(4.3)

4.1.1 MLE for a MVN

=

D
(cid:229)
i=1

1
li

=

D
(cid:229)
i=1

y2
i
li

(x (cid:0) (cid:22))T uiuT

i (x (cid:0) (cid:22))

(4.4)

(4.5)

where yi ≜ uT
lipse in 2d is

i (x (cid:0) (cid:22)). Recall that the equation for an el-

Theorem 4.1. (MLE for a MVN) If we have N iid sam-
ples xi (cid:24) N ((cid:22); (cid:6)), then the MLE for the parameters is
given by

25

26

¯(cid:22) =

¯(cid:6) =

=

1
N

1
N

1
N

N
(cid:229)
i=1
N
(cid:229)
i=1
(

xi ≜ ¯x

(xi (cid:0) ¯x)(xi (cid:0) ¯x)T
)

N
(cid:229)
i=1

xixT
i

(cid:0) ¯x ¯xT

(4.7)

(4.8)

(4.9)

4.1.2 Maximum entropy derivation of the

Gaussian *

In this section, we show that the multivariate Gaussian is
the distribution with maximum entropy subject to having a
speciﬁed mean and covariance (see also Section TODO).
This is one reason the Gaussian is so widely used: the ﬁrst
two moments are usually all that we can reliably estimate
from data, so we want a distribution that captures these
properties, but otherwise makes as few addtional assump-
tions as possible.

To simplify notation, we will assume the mean is zero.

The pdf has the form

f (x) =

(

(cid:0) 1
2

1
Z

exp

)

xT (cid:6)(cid:0)1x

(4.10)

4.2 Gaussian discriminant analysis

One important application of MVNs is to deﬁne the the
class conditional densities in a generative classiﬁer, i.e.,

p(xjy = c; (cid:18)) = N (xj(cid:22)c; (cid:6)c)

(4.11)

The resulting technique is called (Gaussian) discrim-
inant analysis or GDA (even though it is a generative,
not discriminative, classiﬁer see Section TODO for more
on this distinction). If (cid:6)c is diagonal, this is equivalent to
naive Bayes.

We can classify a feature vector using the following

decision rule, derived from Equation 3.1:

(a)

(b)

Fig. 4.2: (a) Height/weight data. (b) Visualization of 2d
Gaussians ﬁt to each class. 95% of the probability mass
is inside the ellipse.

are correlated, as is to be expected (tall people tend to
weigh more). The ellipses for each class contain 95%
of the probability mass. If we have a uniform prior over
classes, we can classify a new test vector as follows:

y = arg max

c

(x (cid:0) (cid:22)c)T (cid:6)(cid:0)1

c (x (cid:0) (cid:22)c)

(4.13)

y = arg max

c

[log p(y = cj(cid:25)) + log p(xj(cid:18))]

(4.12)

4.2.1 Quadratic discriminant analysis

When we compute the probability of x under each
class conditional density, we are measuring the distance
from x to the center of each class, (cid:22)c, using Mahalanobis
distance. This can be thought of as a nearest centroids
classiﬁer.

As an example, Figure 4.2 shows two Gaussian class-
conditional densities in 2d, representing the height and
weight of men and women. We can see that the features

(QDA)

By plugging in the deﬁnition of the Gaussian density to
Equation 3.1, we can get

p(yjx; (cid:18)) =

pcj2p(cid:6)cj(cid:0) 1
(cid:229)c′ pc′j2p(cid:6)c′j(cid:0) 1

2 exp

2 exp

]
[
2 (x (cid:0) (cid:22))T (cid:6)(cid:0)1(x (cid:0) (cid:22))
(cid:0) 1
[
(cid:0) 1

]
2 (x (cid:0) (cid:22))T (cid:6)(cid:0)1(x (cid:0) (cid:22))

(4.14)

Thresholding this results in a quadratic function of
x. The result is known as quadratic discriminant analy-
sis(QDA). Figure 4.3 gives some examples of what the
decision boundaries look like in 2D.

p(yjx; (cid:18)) (cid:181) pc exp
(

xT (cid:6)(cid:0)1x (cid:0) 1
2

(
(cid:22)c(cid:6)(cid:0)1x (cid:0) 1
2
(cid:22)c(cid:6)(cid:0)1x (cid:0) 1
c (cid:6)(cid:0)1(cid:22)c + log pc
(cid:22)T
2
)

27

)

c (cid:6)(cid:0)1(cid:22)c
(cid:22)T
)

(

= exp

exp

(cid:181) exp

xT (cid:6)(cid:0)1x

(cid:0) 1
2
(
(cid:22)c(cid:6)(cid:0)1x (cid:0) 1
2

c (cid:6)(cid:0)1(cid:22)c + log pc
(cid:22)T

)

(4.15)

Since the quadratic term xT (cid:6)(cid:0)1x is independent of c,
it will cancel out in the numerator and denominator. If we
deﬁne

gc ≜ (cid:0) 1
c (cid:6)(cid:0)1(cid:22)c + log pc
(cid:22)T
2
(cid:12)c ≜ (cid:6)(cid:0)1(cid:22)c

(4.16)

(4.17)

(a)

then we can write

p(yjx; (cid:18)) =

e(cid:12)T
(cid:229)c′ e(cid:12)T

c x+gc
c′ x+g
c′

≜ s((cid:17); c)

(4.18)

1 x + g1; (cid:1) (cid:1) (cid:1) ; e(cid:12)T
where (cid:17) ≜ (e(cid:12)T
activation function16, deﬁned as follows:

C x + gC), s() is the softmax

s(q; i) ≜ exp(qi)
(cid:229)n

j=1 exp(q j)

(4.19)

When parameterized by some constant, a > 0, the fol-
lowing formulation becomes a smooth, differentiable ap-
proximation of the maximum function:

Sa(x) =

j=1 x jeax j
(cid:229)D
j=1 eax j
(cid:229)D

(4.20)

Sa has the following properties:

1. Sa ! max as a ! ¥
2. S0 is the average of its inputs
3. Sa ! min as a ! (cid:0)¥

Note that the softmax activation function comes from
the area of statistical physics, where it is common to use
the Boltzmann distribution, which has the same form as
the softmax activation function.

An interesting property of Equation 4.18 is that, if we
take logs, we end up with a linear function of x. (The
reason it is linear is because the xT (cid:6)(cid:0)1x cancels from the
numerator and denominator.) Thus the decision boundary
between any two classes, says c and c′, will be a straight
line. Hence this technique is called linear discriminant
analysis or LDA.

16

http://en.wikipedia.org/wiki/Softmax_

activation_function

(b)

Fig. 4.3: Quadratic decision boundaries in 2D for the 2
and 3 class case.

4.2.2 Linear discriminant analysis (LDA)

We now consider a special case in which the covariance
matrices are tied or shared across classes,(cid:6)c = (cid:6). In this
case, we can simplify Equation 4.14 as follows:

28

An alternative to ﬁtting an LDA model and then de-
riving the class posterior is to directly ﬁt p(yjx; W ) =
Cat(yjW x) for some C (cid:2) D weight matrix W . This is
called multi-class logistic regression, or multinomial lo-
gistic regression. We will discuss this model in detail
in Section TODO. The difference between the two ap-
proaches is explained in Section TODO.

4.2.3 Two-class LDA

To gain further insight into the meaning of these equa-
tions, let us consider the binary case. In this case, the pos-
terior is given by

p(y = 1jx; (cid:18)) =

=

)

e(cid:12)T
1 x+g1
0 x+g0 + e(cid:12)T

e(cid:12)T

1 x+g1
1
1 + e((cid:12)0 (cid:0) (cid:12)1)T x + (g0 (cid:0) g1)

(4.21)

(4.22)

= sigm(((cid:12)1 (cid:0) (cid:12)0)T x + (g0 (cid:0) g1)) (4.23)

where sigm(x) refers to the sigmoid function17.

Now
g1 (cid:0) g0 = (cid:0) 1
2

1 (cid:6)(cid:0)1(cid:22)1 +
(cid:22)T

1
2

0 (cid:6)(cid:0)1(cid:22)0 + log(p1=p0)
(cid:22)T

(4.24)

= (cid:0) 1
2

((cid:22)1 (cid:0) (cid:22)0)T (cid:6)(cid:0)1((cid:22)1 + (cid:22)0) + log(p1=p0)
(4.25)

So if we deﬁne

w = (cid:12)1 (cid:0) (cid:12)0 = (cid:6)(cid:0)1((cid:22)1 (cid:0) (cid:22)0)

(4.26)

x0 =

1
2

((cid:22)1 + (cid:22)0) (cid:0) ((cid:22)1 (cid:0) (cid:22)0)

log(p1=p0)
((cid:22)1 (cid:0) (cid:22)0)T (cid:6)(cid:0)1((cid:22)1 (cid:0) (cid:22)0)
(4.27)

Fig. 4.4: Geometry of LDA in the 2 class case where
(cid:6)1 = (cid:6)2 = I.

closer to (cid:22)0, so more of the line belongs to class 1 a priori.
Conversely if (cid:25)1 < (cid:25)0, the boundary shifts right. Thus we
see that the class prior, c, just changes the decision thresh-
old, and not the overall geometry, as we claimed above.
(A similar argument applies in the multi-class case.)

The magnitude of w determines the steepness of the
logistic function, and depends on how well-separated the
means are, relative to the variance. In psychology and sig-
nal detection theory, it is common to deﬁne the discrim-
inability of a signal from the background noise using a
quantity called d-prime:

d′ ≜

m1 (cid:0) m0
s

(4.29)

where m1 is the mean of the signal and m0 is the mean of
the noise, and s is the standard deviation of the noise. If
d′ is large, the signal will be easier to discriminate from
the noise.

4.2.4 MLE for discriminant analysis

then we have wT x0 = (cid:0)(g1 (cid:0) g0), and hence

The log-likelihood function is as follows:

p(y = 1jx; (cid:18)) = sigm(wT (x (cid:0) x0))

(4.28)

p(Dj(cid:18)) =

C
(cid:229)
c=1

(cid:229)
i:yi=c

log pc +

C
(cid:229)
c=1

(cid:229)
i:yi=c

log N (xij(cid:22)c; (cid:6)c)

(This is closely related to logistic regression, which we
will discuss in Section TODO.) So the ﬁnal decision rule
is as follows: shift x by x0, project onto the line w, and
see if the result is positive or negative.

If (cid:6) = s2I, then w is in the direction of (cid:22)1 (cid:0) (cid:22)0. So
we classify the point based on whether its projection is
closer to (cid:22)0 or (cid:22)1 . This is illustrated in Figure 4.4. Fur-
themore, if (cid:25)1 = (cid:25)0, then x0 = 1
2 ((cid:22)1 + (cid:22)0), which is half
way between the means. If we make (cid:25)1 > (cid:25)0, then x0 gets

17

function

http://en.wikipedia.org/wiki/Sigmoid_

The MLE for each parameter is as follows:

¯(cid:22)c =

¯(cid:22)c =

¯(cid:6)c =

Nc
N
1
Nc

1
Nc

xi

(cid:229)
i:yi=c
(cid:229)
i:yi=c

(xi (cid:0) ¯(cid:22)c)(xi (cid:0) ¯(cid:22)c)T

(4.30)

(4.31)

(4.32)

(4.33)

4.2.5 Strategies for preventing overﬁtting

4.3 Inference in jointly Gaussian

distributions

29

The speed and simplicity of the MLE method is one of its
greatest appeals. However, the MLE can badly overﬁt in
high dimensions. In particular, the MLE for a full covari-
ance matrix is singular if Nc < D. And even when Nc > D,
the MLE can be ill-conditioned, meaning it is close to sin-
gular. There are several possible solutions to this problem:

• Use a diagonal covariance matrix for each class, which
assumes the features are conditionally independent;
this is equivalent to using a naive Bayes classiﬁer (Sec-
tion 3.5).

• Use a full covariance matrix, but force it to be the same
for all classes,(cid:6)c = (cid:6). This is an example of param-
eter tying or parameter sharing, and is equivalent to
LDA (Section 4.2.2).

• Use a diagonal covariance matrix and forced it to be
shared. This is called diagonal covariance LDA, and is
discussed in Section TODO.

• Use a full covariance matrix, but impose a prior and
then integrate it out. If we use a conjugate prior, this
can be done in closed form, using the results from Sec-
tion TODO; this is analogous to the Bayesian naive
Bayes method in Section 3.5.1.2. See (Minka 2000f)
for details.

• Fit a full or diagonal covariance matrix by MAP esti-
mation. We discuss two different kindsof prior below.
• Project the data into a low dimensional subspace and
ﬁt the Gaussians there. See Section TODO for a way
to ﬁnd the best (most discriminative) linear projection.

We discuss some of these options below.

4.2.6 Regularized LDA *

4.2.7 Diagonal LDA

4.2.8 Nearest shrunken centroids classiﬁer *

One drawback of diagonal LDA is that it depends on all of
the features. In high dimensional problems, we might pre-
fer a method that only depends on a subset of the features,
for reasons of accuracy and interpretability. One approach
is to use a screening method, perhaps based on mutual in-
formation, as in Section 3.5.4. We now discuss another
approach to this problem known as the nearest shrunken
centroids classiﬁer (Hastie et al. 2009, p652).

Given a joint distribution, p(x1; x2), it is useful to be able
to compute marginals p(x1) and conditionals p(x1jx2).
We discuss how to do this below, and then give some ap-
plications. These operations take O(D3) time in the worst
case. See Section TODO for faster methods.

4.3.1 Statement of the result

Theorem 4.2. (Marginals and conditionals of an MVN).
Suppose X = (x1; x2)is jointly Gaussian with parameters
)

)

(

)

(

(

(cid:22) =

; (cid:6) =

(cid:22)1
(cid:22)2

(cid:6)11 (cid:6)12
(cid:6)21 (cid:6)22

; (cid:3) = (cid:6)(cid:0)1 =

(cid:3)11 (cid:3)12
(cid:3)21 (cid:3)22
(4.34)

;

Then the marginals are given by

p(x1) = N (x1j(cid:22)1; (cid:6)11)
p(x2) = N (x2j(cid:22)2; (cid:6)22)

(4.35)

and the posterior conditional is given by

p(x1jx2) = N (x1j(cid:22)1j2; (cid:6)1j2)
(cid:22)1j2 = (cid:22)1 + (cid:6)12(cid:6)(cid:0)1
= (cid:22)1 (cid:0) (cid:3)(cid:0)1
= (cid:6)1j2((cid:3)11(cid:22)1 (cid:0) (cid:3)12(x2 (cid:0) (cid:22)2))

22 (x2 (cid:0) (cid:22)2)
11 (cid:3)12(x2 (cid:0) (cid:22)2)

(4.36)

(cid:6)1j2 = (cid:6)11 (cid:0) (cid:6)12(cid:6)(cid:0)1

22 (cid:6)21 = (cid:3)(cid:0)1

11

Equation 4.36 is of such crucial importance in this
book that we have put a box around it, so you can eas-
ily ﬁnd it. For the proof, see Section TODO.

We see that both the marginal and conditional distribu-
tions are themselves Gaussian. For the marginals, we just
extract the rows and columns corresponding to x1 or x2.
For the conditional, we have to do a bit more work. How-
ever, it is not that complicated: the conditional mean is just
a linear function of x2, and the conditional covariance is
just a constant matrix that is independent of x2. We give
three different (but equivalent) expressions for the poste-
rior mean, and two different (but equivalent) expressions
for the posterior covariance; each one is useful in different
circumstances.

30

4.3.2 Examples

4.5 Digression: The Wishart distribution *

Below we give some examples of these equations in ac-
tion, which will make them seem more intuitive.

4.6 Inferring the parameters of an MVN

4.6.1 Posterior distribution of m

4.6.2 Posterior distribution of S *

4.6.3 Posterior distribution of m and S *

4.6.4 Sensor fusion with unknown precisions

*

4.3.2.1 Marginals and conditionals of a 2d Gaussian

4.4 Linear Gaussian systems

Suppose we have two variables, x and y.Let x 2 RDx be a
hidden variable, and y 2 RDy be a noisy observation of x.
Let us assume we have the following prior and likelihood:

p(x) = N (xj(cid:22)x; (cid:6)x)

p(yjx) = N (yjW x + (cid:22)y; (cid:6)y)

(4.37)

where W is a matrix of size Dy (cid:2) Dx. This is an exam-
ple of a linear Gaussian system. We can represent this
schematically as x ! y, meaning x generates y. In this
section, we show how to invert the arrow, that is, how to
infer x from y. We state the result below, then give sev-
eral examples, and ﬁnally we derive the result. We will see
many more applications of these results in later chapters.

4.4.1 Statement of the result

Theorem 4.3. (Bayes rule for linear Gaussian systems).
Given a linear Gaussian system, as in Equation 4.37, the
posterior p(xjy) is given by the following:

p(xjy) = N (xj(cid:22)xjy; (cid:6)xjy)
x + W T (cid:6)(cid:0)1
[
W T (cid:6)(cid:0)1

(cid:6)xjy = (cid:6)(cid:0)1
(cid:22)xjy = (cid:6)xjy

y W
y (y (cid:0) (cid:22)y) + (cid:6)(cid:0)1

x (cid:22)x

(4.38)

]

In addition, the normalization constant p(y) is given by

p(y) = N (yjW (cid:22)x + (cid:22)y; (cid:6)y + W (cid:6)xW T )

(4.39)

For the proof, see Section 4.4.3 TODO.

Chapter 5
Bayesian statistics

5.1 Introduction

5.2.1.1 No measure of uncertainty

Using the posterior distribution to summarize everything
we know about a set of unknown variables is at the core
of Bayesian statistics. In this chapter, we discuss this ap-
proach to statistics in more detail.

5.2 Summarizing posterior distributions

The posterior p((cid:18)jD) summarizes everything we know
about the unknown quantities (cid:18). In this section, we dis-
cuss some simple quantities that can be derived from a
probability distribution, such as a posterior. These sum-
mary statistics are often easier to understand and visualize
than the full joint.

5.2.1 MAP estimation

We can easily compute a point estimate of an unknown
quantity by computing the posterior mean, median or
mode. In Section 5.7, we discuss how to use decision the-
ory to choose between these methods. Typically the pos-
terior mean or median is the most appropriate choice for a
realvalued quantity, and the vector of posterior marginals
is the best choice for a discrete quantity. However, the
posterior mode, aka the MAP estimate, is the most pop-
ular choice because it reduces to an optimization prob-
lem, for which efﬁcient algorithms often exist. Futher-
more, MAP estimation can be interpreted in non-Bayesian
terms, by thinking of the log prior as a regularizer (see
Section TODO for more details).

Although this approach is computationally appealing,
it is important to point out that there are various draw-
backs to MAP estimation, which we brieﬂy discuss be-
low. This will provide motivation for the more thoroughly
Bayesian approach which we will study later in this chap-
ter(and elsewhere in this book).

The most obvious drawback of MAP estimation, and in-
deed of any other point estimate such as the posterior
mean or median, is that it does not provide any measure of
uncertainty. In many applications, it is important to know
how much one can trust a given estimate. We can derive
such conﬁdence measures from the posterior, as we dis-
cuss in Section 5.2.2.

5.2.1.2 Plugging in the MAP estimate can result in

overﬁtting

If we dont model the uncertainty in our parameters, then
our predictive distribution will be overconﬁdent. Over-
conﬁdence in predictions is particularly problematic in
situations where we may be risk averse; see Section 5.7
for details.

5.2.1.3 The mode is an untypical point

Choosing the mode as a summary of a posterior distribu-
tion is often a very poor choice, since the mode is usually
quite untypical of the distribution, unlike the mean or me-
dian. The basic problem is that the mode is a point of mea-
sure zero, whereas the mean and median take the volume
of the space into account. See Figure 5.1.

How should we summarize a posterior if the mode is
not a good choice? The answer is to use decision theory,
which we discuss in Section 5.7. The basic idea is to spec-
ify a loss function, where L(q; ˆq) is the loss you incur if
the truth is q and your estimate is ˆq. If we use 0-1 loss
L(q; ˆq) = I(q ̸= ˆq)(see section 1.2.2.1), then the opti-
mal estimate is the posterior mode. 0-1 loss means you
only get points if you make no errors, otherwise you get
nothing: there is no partial credit under this loss function!
For continuous-valued quantities, we often prefer to use
squared error loss, L(q; ˆq) = (q(cid:0) ˆq)2 ; the corresponding
optimal estimator is then the posterior mean, as we show
in Section 5.7. Or we can use a more robust loss func-
tion, L(q; ˆq) = jq (cid:0) ˆqj, which gives rise to the posterior
median.

31

32

(a)

(b)

Fig. 5.1: (a) A bimodal distribution in which the mode is
very untypical of the distribution. The thin blue vertical
line is the mean, which is arguably a better summary of
the distribution, since it is near the majority of the
probability mass. (b) A skewed distribution in which the
mode is quite different from the mean.

Fig. 5.2: Example of the transformation of a density
under a nonlinear transform. Note how the mode of the
transformed distribution is not the transform of the
original mode. Based on Exercise 1.4 of (Bishop 2006b).

see that the mode of the transformed distribution is not
equal to the transform of the original mode.

The MLE does not suffer from this since the likelihood
is a function, not a probability density. Bayesian inference
does not suffer from this problem either, since the change
of measure is taken into account when integrating over the
parameter space.

5.2.1.4 MAP estimation is not invariant to

reparameterization *

A more subtle problem with MAP estimation is that the
result we get depends on how we parameterize the prob-
ability distribution. Changing from one representation
to another equivalent representation changes the result,
which is not very desirable, since the units of measure-
ment are arbitrary (e.g., when measuring distance, we can
use centimetres or inches).

To understand the problem, suppose we compute the
posterior forx. If we deﬁne y=f(x), the distribution for
yis given by Equation 2.44. The dx
dy term is called the
Jacobian, and it measures the change in size of a unit
volume passed through f . Let ˆx = arg maxx px(x) be the
MAP estimate for x. In general it is not the case that
ˆx = arg maxx px(x) is given by f ( ˆx). For example, let X (cid:24)
N (6; 1) and y = f (x), where f (x) = 1=(1 + exp((cid:0)x + 5)).
We can derive the distribution of y using Monte Carlo
simulation (see Section 2.7). The result is shown in Fig-
ure ??. We see that the original Gaussian has become
squashed by the sigmoid nonlinearity. In particular, we

5.2.2 Credible intervals

In addition to point estimates, we often want a measure
of conﬁdence. A standard measure of conﬁdence in some
(scalar) quantity q is the width of its posterior distribu-
tion. This can be measured using a 100(1a)% credible in-
terval, which is a (contiguous) region C = (ℓ; u)(standing
for lower and upper) which contains 1a of the posterior
probability mass, i.e.,

Ca(D) where P(ℓ (cid:20) q (cid:20) u) = 1 (cid:0) a

(5.1)

There may be many such intervals, so we choose one
such that there is (1a)=2 mass in each tail; this is called a
central interval.

If the posterior has a known functional form, we can
compute the posterior central interval using ℓ = F (cid:0)1(a=2)
and u = F (cid:0)1(1 (cid:0) a=2), where F is the cdf of the posterior.
If we dont know the functional form, but we can draw
samples from the posterior, then we can use a Monte Carlo
approximation to the posterior quantiles: we simply sort
the S samples, and ﬁnd the one that occurs at location

a=S along the sorted list. As S ! ¥, this converges to
the true quantile.

People often confuse Bayesian credible intervals with
frequentist conﬁdence intervals. However, they are not the
same thing, as we discuss in Section TODO. In general,
credible intervals are usually what people want to com-
pute, but conﬁdence intervals are usually what they actu-
ally compute, because most people are taught frequentist
statistics but not Bayesian statistics. Fortunately, the me-
chanics of computing a credible interval is just as easy as
computing a conﬁdence interval.

5.2.3 Inference for a difference in

proportions

Sometimes we have multiple parameters, and we are in-
terested in computing the posterior distribution of some
function of these parameters. For example, suppose you
are about to buy something from Amazon.com, and there
are two sellers offering it for the same price. Seller 1 has
90 positive reviews and 10 negative reviews. Seller 2 has 2
positive reviews and 0 negative reviews. Who should you
buy from?18.

On the face of it, you should pick seller 2, but we can-
not be very conﬁdent that seller 2 is better since it has had
so few reviews. In this section, we sketch a Bayesian anal-
ysis of this problem. Similar methodology can be used to
compare rates or proportions across groups for a variety
of other settings.

Let q1 and q2 be the unknown reliabilities of the two
sellers. Since we dont know much about them, well en-
dow them both with uniform priors, qi (cid:24) Beta(1; 1). The
posteriors are p(q1jD1) = Beta(91; 11) and p(q2jD2) =
Beta(3; 1).

We want to compute p(q1 > q2jD). For convenience,
let us deﬁne d = q1 (cid:0) q2 as the difference in the rates.
(Alternatively we might want to work in terms of the log-
odds ratio.) We can compute the desired quantity using
numerical integration
∫

∫

p(d > 0jD) =

1

1

0

0

I(q1 > q2)Beta(q1j91; 11)

(5.2)

Beta(q2j3; 1)dq1dq2

We ﬁnd p(d > 0jD) = 0:710, which means you are

better off buying from seller 1!

18 This example is from http://www.johndcook.com/
blog/2011/09/27/bayesian-amazon/

5.3 Bayesian model selection

33

In general, when faced with a set of models (i.e., families
of parametric distributions) of different complexity, how
should we choose the best one? This is called the model
selection problem.

One approach is to use cross-validation to estimate the
generalization error of all the candidate models, and then
to pick the model that seems the best. However, this re-
quires ﬁtting each model K times, where K is the number
of CV folds. A more efﬁcient approach is to compute the
posterior over models,

p(mjD) =

p(Djm)p(m)
(cid:229)m′ p(Djm′)p(m′)

(5.3)

From this, we can easily compute the MAP model,
ˆm = arg maxm p(mjD). This is called Bayesian model se-
lection.

If we use a uniform prior over models, this amounts to

picking the model which maximizes

∫

p(Djm) =

p(Dj(cid:18))p((cid:18)jm)d(cid:18)

(5.4)

This quantity is called the marginal likelihood, the in-
tegrated likelihood, or the evidence for model m. The de-
tails on how to perform this integral will be discussed in
Section 5.3.2. But ﬁrst we give an intuitive interpretation
of what this quantity means.

5.3.1 Bayesian Occam’s razor

One might think that using p(Djm) to select models
would always favour the model with the most parameters.
This is true if we use p(Dj ˆ(cid:18)m) to select models, where
ˆ(cid:18)m) is the MLE or MAP estimate of the parameters for
model m, because models with more parameters will
ﬁt the data better, and hence achieve higher likelihood.
However, if we integrate out the parameters, rather than
maximizing them, we are automatically protected from
overﬁtting: models with more parameters do not nec-
essarily have higher marginal likelihood. This is called
the Bayesian Occams razor effect (MacKay 1995b;
Murray and Ghahramani 2005), named after the principle
known as Occams razor, which says one should pick the
simplest model that adequately explains the data.

One way to understand the Bayesian Occams razor is
to notice that the marginal likelihood can be rewritten as
follows, based on the chain rule of probability (Equation
2.3):

34

p(D) = p((x1; y1))p((x2; y2)j(x1; y1))
p((x3; y3)j(x1; y1) : (x2; y2)) (cid:1) (cid:1) (cid:1)
p((xN; yN)j(x1; y1) : (xN(cid:0)1; yN(cid:0)1))

5.3.2 Computing the marginal likelihood

(5.5)

(evidence)

This is similar to a leave-one-out cross-validation es-
timate (Section 1.3.4) of the likelihood, since we predict
each future point given all the previous ones. (Of course,
the order of the data does not matter in the above expres-
sion.) If a model is too complex, it will overﬁt the early
examples and will then predict the remaining ones poorly.
Another way to understand the Bayesian Occams ra-
zor effect is to note that probabilities must sum to one.
Hence (cid:229)p(D′) p(mjD′) = 1, where the sum is over all
possible data sets. Complex models, which can predict
many things, must spread their probability mass thinly,
and hence will not obtain as large a probability for any
given data set as simpler models. This is sometimes called
the conservation of probability mass principle, and is il-
lustrated in Figure 5.3.

Fig. 5.3: A schematic illustration of the Bayesian
Occams razor. The broad (green) curve corresponds to a
complex model, the narrow (blue) curve to a simple
model, and the middle (red) curve is just right. Based on
Figure 3.13 of (Bishop 2006a).

When using the Bayesian approach, we are not re-
stricted to evaluating the evidence at a ﬁnite grid of val-
ues. Instead, we can use numerical optimization to ﬁnd
l(cid:3) = arg maxl p(Djl). This technique is called empir-
ical Bayes or type II maximum likelihood (see Section
5.6 for details). An example is shown in Figure TODO(b):
we see that the curve has a similar shape to the CV esti-
mate, but it can be computed more efﬁciently.

When discussing parameter inference for a ﬁxed model,
we often wrote

p((cid:18)jD; m) (cid:181) p((cid:18)jm)p(Dj(cid:18); m)

(5.6)

thus ignoring the normalization constant p(Djm). This
is valid since p(Djm)is constant wrt (cid:18). However, when
comparing models, we need to know how to compute the
marginal likelihood, p(Djm). In general, this can be quite
hard, since we have to integrate over all possible parame-
ter values, but when we have a conjugate prior, it is easy
to compute, as we now show.

Let p((cid:18)) = q((cid:18))=Z0 be our prior, where q((cid:18)) is an un-
normalized distribution, and Z0 is the normalization con-
stant of the prior. Let p(Dj(cid:18)) = q(Dj(cid:18))=Zℓ be the likeli-
hood, where Zℓ contains any constant factors in the like-
lihood. Finally let p((cid:18)jD) = q((cid:18)jD)=ZN be our posterior
, where q((cid:18)jD) = q(Dj(cid:18))q((cid:18)) is the unnormalized poste-
rior, and ZN is the normalization constant of the posterior.
We have

p((cid:18)jD) =

q((cid:18)jD)
ZN

=

p(D) =

p(Dj(cid:18))p((cid:18))
p(D)
q(Dj(cid:18))q((cid:18))
ZℓZ0 p(D)
ZN
Z0Zℓ

(5.7)

(5.8)

(5.9)

So assuming the relevant normalization constants are
tractable, we have an easy way to compute the marginal
likelihood. We give some examples below.

5.3.2.1 Beta-binomial model

Let us apply the above result to the Beta-binomial model.
Since we know p((cid:18)jD) = Beta((cid:18)ja′; b′), where a′ = a +
N1, b′ = b + N0, we know the normalization constant of
the posterior is B(a′; b′). Hence

p(qjD) =

=

=

p(Djq)p(q)
p(D)
[

(5.10)

]

qa(cid:0)1(1 (cid:0) q)b(cid:0)1
]

1
B(a; b)

qN1 (1 (cid:0) q)N0
[
qa+N1(cid:0)1(1 (cid:0) q)b+N0(cid:0)1

(5.11)
]

1
p(D)

1
B(a; b)

(5.12)

)

1
p(D)
[(
N
N1
)
N
N1

(

So

1
B(a + N1; b + N0)

=

p(D) =

)

)

1
1
p(D)
B(a; b)
B(a + N1; b + N0)
B(a; b)

(5.13)

(5.14)

penalty term depends on the models complexity. See Sec-
tion TODO for the derivation of the BIC score.

As an example, consider
we show in Section TODO,
ˆw = (X T X)(cid:0)1X T y and s2 = 1
N
corresponding log likelihood is given by

linear
regression. As
the MLE is given by
i=1(yi (cid:0) ˆwT xi). The
(cid:229)N

35

(

(

N
N1
N
N1

The marginal likelihood for the Beta-Bernoulli model

is the same as above, except it is missingthe

term.

(

)

N
N1

log p(Dj ˆ(cid:18)) = (cid:0) N
2

log(2p ˆs2) (cid:0) N
2

(5.21)

Hence the BIC score is as follows (dropping constant

5.3.2.2 Dirichlet-multinoulli model

terms)

By the same reasoning as the Beta-Bernoulli case, one
can show that the marginal likelihood for the Dirichlet-
multinoulli model is given by

p(D) =

=

B(N + (cid:11))
B((cid:11))
G((cid:229)k ak)
G(N + (cid:229)k ak)

G(Nk + ak)
G(ak)

(cid:213)
k

(5.15)

(5.16)

5.3.2.3 Gaussian-Gaussian-Wishart model

Consider the case of an MVN with a conjugate NIW prior.
Let Z0 be the normalizer for the prior, ZN be normalizer
for the posterior, and let Zℓ(2p)ND=2 = be the normalizer
for the likelihood. Then it is easy to see that

p(D) =

ZN
Z0Zℓ

=

1
(2p)ND=2

(

2p
kN
(

(5.17)

)

D=2

)

2p
k0

jSNj(cid:0)nN =22(n0+N)D=2GD(nN=2)
D=2

jS0j(cid:0)n0=22n0D=2GD(n0=2)
(5.18)

=

1
pND=2

)

(

k0
kN

D=2 jS0jn0=2
jSNjnN =2

GD(nN=2)
GD(n0=2)

(5.19)

5.3.2.4 BIC approximation to log marginal likelihood

In general, computing the integral in Equation 5.4 can be
quite difﬁcult. One simple but popular approximation is
known as the Bayesian information criterion or BIC,
which has the following form (Schwarz 1978):

BIC ≜ log p(Dj ˆ(cid:18)) (cid:0) dof( ˆ(cid:18))

2

log N

(5.20)

where dof( ˆ(cid:18)) is the number of degrees of freedom in
the model, and ˆ(cid:18) is the MLE for the model. We see that
this has the form of a penalized log likelihood, where the

BIC = (cid:0) N
2

log( ˆs2) (cid:0) D
2

log N

(5.22)

where D is the number of variables in the model. In the
statistics literature, it is common to use an alternative def-
inition of BIC, which we call the BIC cost(since we want
to minimize it):

BIC-cost ≜ (cid:0)2 log p(Dj ˆ(cid:18)) (cid:0) dof( ˆ(cid:18)) log N (cid:25) (cid:0)2 log p(D)
(5.23)

In the context of linear regression, this becomes

BIC-cost = N log( ˆs2) + D log N

(5.24)

The BIC method is very closely related to the mini-
mum description length or MDL principle, which char-
acterizes the score for a model in terms of how well it ﬁts
the data, minus how complex the model is to deﬁne. See
(Hansen and Yu 2001) for details.

There is a very similar expression to BIC/ MDL called

the Akaike information criterion or AIC, deﬁned as

AIC(m; D) = log p(Dj ˆ(cid:18)MLE ) (cid:0) dof(m)

(5.25)

This is derived from a frequentist framework, and can-
not be interpreted as an approximation to the marginal
likelihood. Nevertheless, the form of this expression is
very similar to BIC. We see that the penalty for AIC is
less than for BIC. This causes AIC to pick more complex
models. However, this can result in better predictive ac-
curacy. See e.g., (Clarke et al. 2009, sec 10.2) for further
discussion on such information criteria.

5.3.2.5 Effect of the prior

Sometimes it is not clear how to set the prior. When
we are performing posterior inference, the details of the
prior may not matter too much, since the likelihood often
overwhelms the prior anyway. But when computing the
marginal likelihood, the prior plays a much more impor-
tant role, since we are averaging the likelihood over all
possible parameter settings, as weighted by the prior.

36

If the prior is unknown, the correct Bayesian procedure
is to put a prior on the prior. If the prior is unknown, the
correct Bayesian procedure is to put a prior on the prior.

5.3.3 Bayes factors

Suppose our prior on models is uniform, p(m) (cid:181) 1. Then
model selection is equivalent to picking the model with
the highest marginal likelihood. Now suppose we just
have two models we are considering, call them the null
hypothesis, M0, and the alternative hypothesis, M1. De-
ﬁne the Bayes factor as the ratio of marginal likelihoods:

BF1;0 ≜ p(DjM1)
p(DjM0)

=

p(M1jD)
p(M2jD)

=

p(M1)
p(M0)

(5.26)

5.4 Priors

The most controversial aspect of Bayesian statistics is its
reliance on priors. Bayesians argue this is unavoidable,
since nobody is a tabula rasa or blank slate: all inference
must be done conditional on certain assumptions about
the world. Nevertheless, one might be interested in mini-
mizing the impact of ones prior assumptions. We brieﬂy
discuss some ways to do this below.

5.4.3 Mixtures of conjugate priors

Robust priors are useful, but can be computationally ex-
pensive to use. Conjugate priors simplify the computation,
but are often not robust, and not ﬂexible enough to en-
code our prior knowledge. However, it turns out that a
mixture of conjugate priors is also conjugate, and can
approximate any kind of prior (Dallal and Hall 1983;
Diaconis and Ylvisaker 1985). Thus such priors provide
a good compromise between computational convenience
and ﬂexibility.

5.5 Hierarchical Bayes

A key requirement for computing the posterior p((cid:18)jD) is
the speciﬁcation of a prior p((cid:18)j(cid:17)), where (cid:17) are the hyper-
parameters. What if we dont know how to set (cid:17)? In some
cases, we can use uninformative priors, we we discussed
above. A more Bayesian approach is to put a prior on our
priors! In terms of graphical models (Chapter TODO), we
can represent the situation as follows:

(cid:17) ! (cid:18) ! D

(5.27)

This is an example of a hierarchical Bayesian model,
also called a multi-level model, since there are multiple
levels of unknown quantities.

5.4.1 Uninformative priors

5.6 Empirical Bayes

If we dont have strong beliefs about what q should be, it
is common to use an uninformative or non-informative
prior, and to let the data speak for itself.

Method

Deﬁnition

5.4.2 Robust priors

In many cases, we are not very conﬁdent in our prior, so
we want to make sure it does not have an undue inﬂu-
ence on the result. This can be done by using robust pri-
ors(Insua and Ruggeri 2000), which typically have heavy
tails, which avoids forcing things to be too close to the
prior mean.

Maximum likelihood
MAP estimation

ML-II (Empirical Bayes)

MAP-II

Full Bayes

ˆ(cid:18) = arg max(cid:18) p(Dj(cid:18))
ˆ(cid:18) = arg max(cid:18) p(Dj(cid:18))p((cid:18)j(cid:17))
∫
ˆ(cid:17) = arg max(cid:17)

p(Dj(cid:18))p((cid:18)j(cid:17))d(cid:18)

= arg max(cid:17) p(Dj(cid:17))

∫

ˆ(cid:17) = arg max(cid:17)

p(Dj(cid:18))p((cid:18)j(cid:17))p((cid:17))d(cid:18)

= arg max(cid:17) p(Dj(cid:17))p((cid:17))
p((cid:18); (cid:17)jD) (cid:181) p(Dj(cid:18))p((cid:18)j(cid:17))

5.7 Bayesian decision theory

We have seen how probability theory can be used to rep-
resent and updates our beliefs about the state of the world.
However, ultimately our goal is to convert our beliefs into

actions. In this section, we discuss the optimal way to do
this.

Our goal is to devise a decision procedure or pol-
icy, f (x) : X ! Y, which minimizes the expected loss
Rexp( f )(see Equation 1.1).

In the Bayesian approach to decision theory, the opti-
mal output, having observed x, is deﬁned as the output a
that minimizes the posterior expected loss:

r( f ) = Ep(yjx)[L(y; f (x))] =

8
><
(cid:229)
y
∫
>:

L[y; f (x)]p(yjx)

L[y; f (x)]p(yjx)dy

(5.28)
Hence the Bayes estimator, also called the Bayes de-

y

cision rule, is given by

d(x) = arg min
f 2H

r( f )

(5.29)

r( f ) =

=

=

∫

y
∫

y
∫

y

L[y; f (x)]p(yjx)dy

[y (cid:0) f (x)]2 p(yjx)dy

[
y2 (cid:0) 2y f (x) + f (x)2

]

p(yjx)dy

37

(5.30)

Hence the optimal estimate is the posterior mean:

[(cid:0)2y + 2 f (x)]p(yjx)dy = 0 )

=

∫

y

¶r
¶ f
∫

y

f (x)

∫

y

f (x)p(yjx)dy =

∫

y

yp(yjx)dy

p(yjx)dy = Ep(yjx)[y]

5.7.1 Bayes estimators for common loss

This is often called the minimum mean squared er-

functions

ror estimate or MMSE estimate.

f (x) = Ep(yjx)[y]

(5.31)

5.7.1.1 MAP estimate minimizes 0-1 loss

When L(y; f (x)) is 0-1 loss(Section 1.2.2.1), we can proof
that MAP estimate minimizes 0-1 loss,

arg min
f 2H

r( f ) = arg min
f 2H

= arg min
f 2H

= arg min
f 2H

= arg min
f 2H

I( f (x) ̸= Ck)p(Ckjx)

L[Ck; f (x)]p(Ckjx)

K
(cid:229)
i=1
K
(cid:229)
i=1
K
(cid:229)
i=1
[1 (cid:0) p( f (x) = Ckjx)]

p( f (x) ̸= Ckjx)

= arg max
f 2H

p( f (x) = Ckjx)

5.7.1.2 Posterior mean minimizes ℓ2(quadratic) loss

For continuous parameters, a more appropriate loss func-
tion is squared error, ℓ2 loss, or quadratic loss, deﬁned
as L(y; f (x)) = [y (cid:0) f (x)]2.

The posterior expected loss is given by

5.7.1.3 Posterior median minimizes ℓ1(absolute) loss

The ℓ2 loss penalizes deviations from the truth quadrat-
ically, and thus is sensitive to outliers. A more robust
alternative is the absolute or ℓ1 loss. The optimal esti-
mate is the posterior median, i.e., a value a such that
P(y < ajx) = P(y (cid:21) ajx) = 0:5.

Proof.

r( f ) =

∫

y
∫

L[y; f (x)]p(yjx)dy =

∫

y

jy (cid:0) f (x)jp(yjx)dy

=

[ f (x) (cid:0) y]p(y < f (x)jx)+

y
[y (cid:0) f (x)]p(y (cid:21) f (x)jx)dy

∫

¶r
¶ f

=

[p(y < f (x)jx) (cid:0) p(y (cid:21) f (x)jx)] dy = 0 )

y

p(y < f (x)jx) = p(y (cid:21) f (x)jx) = 0:5
) f (x) = median

5.7.1.4 Reject option

In classiﬁcation problems where p(yjx) is very uncer-
tain, we may prefer to choose a reject action, in which
we refuse to classify the example as any of the speciﬁed
classes, and instead say dont know. Such ambiguous cases

38

can be handled by e.g., a human expert. This is useful in
risk averse domains such as medicine and ﬁnance.

We can formalize the reject option as follows. Let
choosing f (x) = cK+1 correspond to picking the reject ac-
tion, and choosing f (x) 2 fC1; :::;Ckg correspond to pick-
ing one of the classes. Suppose we deﬁne the loss function
as

L( f (x); y) =

8
><
0
ls
lr

>:

if f (x) = y and f (x); y 2 fC1; :::;Ckg
if f (x) ̸= y and f (x); y 2 fC1; :::;Ckg
if f (x) = CK+1

(5.32)
where ls is the cost of a substitution error, and lr is the
cost of the reject action.

5.7.1.5 Supervised learning

We can deﬁne the loss incurred by f (x) (i.e., using this
predictor) when the unknown state of nature is (cid:18)(the pa-
rameters of the data generating mechanism) as follows:

L((cid:18); f ) ≜ Ep(x;yj(cid:18))[ℓ(y (cid:0) f (x))]

(5.33)

This is known as the generalization error. Our goal is

to minimize the posterior expected loss, given by
∫

r( f jD) =

p((cid:18)jD)L((cid:18); f )d(cid:18)

(5.34)

This should be contrasted with the frequentist risk

which is deﬁned in Equation TODO.

5.7.2 The false positive vs false negative

tradeoff

In this section, we focus on binary decision problems,
such as hypothesis testing, two-class classiﬁcation, object/
event detection, etc. There are two types of error we can
make: a false positive(aka false alarm), or a false nega-
tive(aka missed detection). The 0-1 loss treats these two
kinds of errors equivalently. However, we can consider the
following more general loss matrix:

TODO

Chapter 6
Frequentist statistics

Attempts have been made to devise approaches to sta-
tistical inference that avoid treating parameters like ran-
dom variables, and which thus avoid the use of priors and
Bayes rule. Such approaches are known as frequentist
statistics, classical statistics or orthodox statistics. In-
stead of being based on the posterior distribution, they are
based on the concept of a sampling distribution.

6.1 Sampling distribution of an estimator

In frequentist statistics, a parameter estimate ˆ(cid:18) is com-
puted by applying an estimator d to some data D, so
ˆ(cid:18) = d(D). The parameter is viewed as ﬁxed and the data
as random, which is the exact opposite of the Bayesian
approach. The uncertainty in the parameter estimate can
be measured by computing the sampling distribution of
the estimator. To understand this

6.1.1 Bootstrap

We might think of the bootstrap distribution as a poor
mans Bayes posterior, see (Hastie et al. 2001, p235) for
details.

Rexp(q; f ) ≜ E
∫

=

p( ˜Djq(cid:3))[L(q(cid:3); f ( ˜D))]
L(q(cid:3); f ( ˜D))p( ˜Djq(cid:3))d ˜D

(6.1)

where ˜D is data sampled from natures distribution, which
is represented by parameter q(cid:3). In other words, the ex-
pectation is wrt the sampling distribution of the estimator.
Compare this to the Bayesian posterior expected loss:

r( f jD; )

(6.2)

6.3 Desirable properties of estimators

6.4 Empirical risk minimization

6.4.1 Regularized risk minimization

6.4.2 Structural risk minimization

6.4.3 Estimating the risk using cross

validation

6.4.4 Upper bounding the risk using
statistical learning theory *

6.1.2 Large sample theory for the MLE *

6.4.5 Surrogate loss functions

6.2 Frequentist decision theory

log-loss

In frequentist or classical decision theory, there is a loss
function and a likelihood, but there is no prior and hence
no posterior or posterior expected loss. Thus there is no
automatic way of deriving an optimal estimator, unlike
the Bayesian case. Instead, in the frequentist approach,
we are free to choose any estimator or decision procedure
f : X ! Y we want.

Having chosen an estimator, we deﬁne its expected loss

or risk as follows:

Lnll(y; h) = (cid:0) log p(yjx; w) = log(1 + e(cid:0)yh)

(6.3)

6.5 Pathologies of frequentist statistics *

39

Chapter 7
Linear Regression

7.1 Introduction

Linear regression is the work horse of statistics and (su-
pervised) machine learning. When augmented with ker-
nels or other forms of basis function expansion, it can
model also nonlinear relationships. And when the Gaus-
sian output is replaced with a Bernoulli or multinoulli dis-
tribution, it can be used for classiﬁcation, as we will see
below. So it pays to study this model in detail.

by

ℓ((cid:18)) =

(

[

N
(cid:229)
i=1

log

1p

2ps

exp

(cid:0) 1
2s2 (yi (cid:0) wT xi)2

)]

= (cid:0) 1

2s2 RSS(w) (cid:0) N

2

log(2ps2)

(7.5)

(7.6)

RSS stands for residual sum of squares and is deﬁned

RSS(w) ≜

N
(cid:229)
i=1

(yi (cid:0) wT xi)2

(7.7)

7.2 Representation

p(yjx; (cid:18)) = N (yjwT x; s2)

(7.1)

where w and x are extended vectors, x = (1; x), w =
(b; w).

Linear regression can be made to model non-linear re-
lationships by replacing x with some non-linear function
of the inputs, ϕ(x)

We see that the MLE for w is the one that minimizes

the RSS, so this method is known as least squares.

Let’s drop constants wrt w and NLL can be written as

NLL(w) =

1
2

N
(cid:229)
i=1

(yi (cid:0) wT xi)2

(7.8)

There two ways to minimize NLL(w).

p(yjx; (cid:18)) = N (yjwT ϕ(x); s2)

(7.2)

7.3.1 OLS

This is known as basis function expansion. (Note that
the model is still linear in the parameters w, so it is still
called linear regression; the importance of this will be-
come clear below.) A simple example are polynomial ba-
sis functions, where the model has the form

ϕ(x) = (1; x; (cid:1) (cid:1) (cid:1) ; xd)

(7.3)

7.3 MLE

Instead of maximizing the log-likelihood, we can equiva-
lently minimize the negative log likelihood or NLL:

NLL((cid:18)) ≜ (cid:0)ℓ((cid:18)) = (cid:0) log(Dj(cid:18))

(7.4)

The NLL formulation is sometimes more convenient,
since many optimization software packages are designed
to ﬁnd the minima of functions, rather than maxima.

Now let us apply the method of MLE to the linear re-
gression setting. Inserting the deﬁnition of the Gaussian
into the above, we ﬁnd that the log likelihood is given by

Deﬁne y = (y1; y2; (cid:1) (cid:1) (cid:1) ; yN), X =

can be written as

1

C
C
C
A, then NLL(w)

0

B
B
B
@

xT
1
xT
2
...
xT
N

NLL(w) =

1
2

(y (cid:0) Xw)T (y (cid:0) Xw)

(7.9)

When D is small(for example, N < 1000), we can use

the following equation to compute w directly

ˆwOLS = (X T X)(cid:0)1X T y

(7.10)

The corresponding solution ˆwOLS to this linear system
of equations is called the ordinary least squares or OLS
solution.

Proof. We now state without proof some facts of matrix
derivatives (we wont need all of these at this section).

41

42

trA ≜

n
(cid:229)
i=1

Aii

¶
¶A

AB = BT
[

¶
¶AT f (A) =
¶
¶A

]
T

f (A)

¶
¶A

ABATC = CAB +CT ABT

¶
¶A

jAj = jAj(A(cid:0)1)T

(7.11)

(7.12)

(7.13)

(7.14)

Then,

NLL(w) =

¶NLL
w

=

=

=

=

w
¶

1
2N
¶
1
2
1
2
1
2
1
2

w
¶

w
¶

w

(Xw (cid:0) y)T (Xw (cid:0) y)

(wT X T Xw (cid:0) wT X T y (cid:0) yT Xw + yT y)

(wT X T Xw (cid:0) wT X T y (cid:0) yT Xw)

tr(wT X T Xw (cid:0) wT X T y (cid:0) yT Xw)

(trwT X T Xw (cid:0) 2tryT Xw)

Fig. 7.1: Graphical interpretation of least squares for
N = 3 examples and D = 2 features. ˜x1 and ˜x2 are
vectors in R3; together they deﬁne a 2D plane. y is also a
vector in R3 but does not lie on this 2D plane. The
orthogonal projection of y onto this plane is denoted ˆy.
The red line from y to ˆy is the residual, whose norm we
want to minimize. For visual clarity, all vectors have
been converted to unit norm.

Combining Equations 7.12 and 7.13, we ﬁnd that

¶
¶AT ABATC = BT ATCT + BATC
Let AT = w; B = BT = X T X, and C = I, Hence,

¶NLL
w

¶NLL
w

=

=

1
2
1
2

(X T Xw + X T Xw (cid:0) 2X T y)

(X T Xw (cid:0) X T y)

= 0 ) X T Xw (cid:0) X T y = 0

X T Xw = X T y

ˆwOLS = (X T X)(cid:0)1X T y

(7.15)

Equation 7.15 is known as the normal equation.

7.3.1.1 Geometric interpretation

See Figure 7.1.

To minimize the norm of the residual, y (cid:0) ˆy, we want
the residual vector to be orthogonal to every column of
X,so ˜x j(y (cid:0) ˆy) = 0 for j = 1 : D. Hence

˜x j(y (cid:0) ˆy) = 0 ) X T (y (cid:0) Xw) = 0

) w = (X T X)(cid:0)1X T y

(7.16)

7.3.2 SGD

When D is large, use stochastic gradient descent(SGD).

∵

¶
¶wi

NLL(w) =

N
(cid:229)
i=1

(wT xi (cid:0) yi)xi j

) w j =w j (cid:0) a

¶
¶w j

NLL(w)

=w j (cid:0)

N
(cid:229)
i=1
) w =w (cid:0) a(wT xi (cid:0) yi)x

a(wT xi (cid:0) yi)xi j

(7.17)

(7.18)

(7.19)

7.4 Ridge regression(MAP)

One problem with ML estimation is that it can result in
overﬁtting. In this section, we discuss a way to ameliorate
this problem by using MAP estimation with a Gaussian
prior.

7.4.1 Basic idea

We can encourage the parameters to be small, thus result-
ing in a smoother curve, by using a zero-mean Gaussian
prior:

p(w) = (cid:213)
j

N (w jj0; t2)

(7.20)

where 1=t2 controls the strength of the prior. The corre-
sponding MAP estimation problem becomes

arg max

w

N
(cid:229)
i=1

log N (yijw0 + wT xi; s2)+

D
(cid:229)
j=1

log N (w jj0; t2)

43

In domains with lots of data, simple methods can work
surprisingly well (Halevy et al. 2009). However, there are
still reasons to study more sophisticated learning methods,
because there will always be problems for which we have
little data. For example, even in such a data-rich domain
as web search, as soon as we want to start personalizing
the results, the amount of data available for any given user
starts to look small again (relative to the complexity of the
problem).

7.5 Bayesian linear regression

(7.21)
It is a simple exercise to show that this is equivalent to

TODO

minimizing the following

1
N

J(w) =

N
(cid:229)
i=1

(yi (cid:0) (w0 + wT xi))2 + l∥w∥2; l ≜

s2
t2
(7.22)
Here the ﬁrst term is the MSE/ NLL as usual, and the
second term, l (cid:21) 0, is a complexity penalty. The corre-
sponding solution is given by

ˆwridge = (lI D + X T X)(cid:0)1X T y

(7.23)

This technique is known as ridge regression,or penal-
ized least squares. In general, adding a Gaussian prior to
the parameters of a model to encourage them to be small
is called ℓ2 regularization or weight decay. Note that the
offset term w0 is not regularized, since this just affects the
height of the function, not its complexity.

We will consider a variety of different priors in this
book. Each of these corresponds to a different form of
regularization. This technique is very widely used to pre-
vent overﬁtting.

7.4.2 Numerically stable computation *

ˆwridge = V (ZT Z + lI N)(cid:0)1ZT y

(7.24)

7.4.3 Connection with PCA *

7.4.4 Regularization effects of big data

Regularization is the most common way to avoid overﬁt-
ting. However, another effective approach which is not
always available is to use lots of data. It should be in-
tuitively obvious that the more training data we have, the
better we will be able to learn.

Chapter 8
Logistic Regression

8.1 Representation

Logistic regression can be binomial or multinomial. The
binomial logistic regression model has the following
form

p(yjx; w) = Ber(yjsigm(wT x))

where w and x are
w = (b; w1; w2; (cid:1) (cid:1) (cid:1) ; wD), x = (1; x1; x2; (cid:1) (cid:1) (cid:1) ; xD).

extended

vectors,

(8.1)

i.e.,

g(w) =

H(w) =

=

=

N
(cid:229)
i=1
d
dw
(cid:25)T X T

=

dJ
dw
dgT
dw
d
dw

[p(xi) (cid:0) yi] xi = X((cid:25) (cid:0) y)

(8.3)

((cid:25) (cid:0) y)T X T

= (p(xi)(1 (cid:0) p(xi))xi; (cid:1) (cid:1) (cid:1) ; )X T
= XSX T ; S ≜ diag(p(xi)(1 (cid:0) p(xi))xi)

(8.4)

8.2 Optimization

8.2.1.1 Iteratively reweighted least squares (IRLS)

8.2.1 MLE

ℓ(w) = log

{

N
(cid:213)
i=1

TODO

}

[p(xi)]yi [1 (cid:0) p(xi)]1(cid:0)yi

8.2.2 MAP

[yi log p(xi) + (1 (cid:0) yi) log(1 (cid:0) p(xi))]
[

]
+ log(1 (cid:0) p(xi))

, where p(x) ≜ P(y = 1jx; w)
N
(cid:229)
i=1
N
(cid:229)
i=1
N
(cid:229)
i=1

p(xi)
1 (cid:0) p(xi)

yi log

=

=

=

[yi(w (cid:1) xi) (cid:0) log(1 + exp(w (cid:1) xi))]

J(w) ≜ NLL(w) = (cid:0)ℓ(w)

Just as we prefer ridge regression to linear regression, so
we should prefer MAP estimation for logistic regression
to computing the MLE. ℓ2 regularization

we can use ℓ2 regularization, just as we did with ridge
regression. We note that the new objective, gradient and
Hessian have the following forms:

J′(w) ≜ NLL(w) + lwT w
g′(w) = g(w) + lw
H ′(w) = H(w) + lI

(8.5)
(8.6)

(8.7)

= (cid:0)

N
(cid:229)
i=1

[yi(w (cid:1) xi) (cid:0) log(1 + exp(w (cid:1) xi))]

(8.2)

It is a simple matter to pass these modiﬁed equations

into any gradient-based optimizer.

Equation 8.2 is also called the cross-entropy error

function (see Equation 2.53).

Unlike linear regression, we can no longer write down
the MLE in closed form. Instead, we need to use an op-
timization algorithm to compute it, see Appendix A. For
this, we need to derive the gradient and Hessian.

In the case of logistic regression, one can show that the

gradient and Hessian of this are given by the following

8.3 Multinomial logistic regression

8.3.1 Representation

Multinomial logistic regression model is also called a
maximum entropy classiﬁer, which has the following
form

45

(8.8)

J′(W ) = NLL(w) (cid:0) log p(W )

(8.15)

, where p(W ) ≜

C
(cid:213)
c=1

N (wcj0; V 0)

= J(W ) +

1
2

C
(cid:229)
c=1

wcV (cid:0)1

0 wc

Its gradient and Hessian are given by

(

)

g′(w) = g(W ) + V (cid:0)1
0

C
(cid:229)
c=1
H ′(w) = H(w) + IC (cid:10) V (cid:0)1
0

wc

(8.16)

(8.17)

(8.18)

(8.19)

This can be passed to any gradient-based optimizer to
ﬁnd the MAP estimate. Note, however, that the Hessian
has size ((CD)(CD)), which is C times more row and
columns than in the binary case, so limited memory BFGS
is more appropriate than Newtons method.

8.4 Bayesian logistic regression

It is natural to want to compute the full posterior over the
parameters, p(wjD), for logistic regression models. This
can be useful for any situation where we want to asso-
ciate conﬁdence intervals with our predictions (e.g., this is
necessary when solving contextual bandit problems, dis-
cussed in Section TODO).

Unfortunately, unlike the linear regression case, this
cannot be done exactly, since there is no convenient con-
jugate prior for logistic regression. We discuss one sim-
ple approximation below; some other approaches include
MCMC (Section TODO), variational inference (Section
TODO), expectation propagation (Kuss and Rasmussen
2005), etc. For notational simplicity, we stick to binary
logistic regression.

46

p(y = cjx; W ) =

8.3.2 MLE

exp(wT
c x)
c=1 exp(wT

(cid:229)C

c x)

Let yi = (I(yi = 1); I(yi = 1); (cid:1) (cid:1) (cid:1) ; I(yi = C)), (cid:22)i = (p(y =
1jxi; W ); p(y = 2jxi; W ); (cid:1) (cid:1) (cid:1) ; p(y = Cjxi; W )), then the
log-likelihood function can be written as

ℓ(W ) = log

N
(cid:213)
i=1
[(

C
(cid:213)
c=1

myic
ic =

N
(cid:229)
i=1
)

C
(cid:229)
c=1

yic log mic
(

(8.9)
)]

=

N
(cid:229)
i=1

C
(cid:229)
c=1

yicwT

c xi

(cid:0) log

C
(cid:229)
c=1

exp(wT

c xi)

(8.10)

Deﬁne the objective function as NLL

J(W ) = NLL(W ) = (cid:0)ℓ(W )

(8.11)

Deﬁne A (cid:10) B be the kronecker product of matrices
A and B.If A is an m (cid:2) n matrix and B is a p (cid:2) q matrix,
then A (cid:10) B is the mp (cid:2) nq block matrix

0

B
@

A (cid:10) B△

a11B (cid:1) (cid:1) (cid:1) a1nB
...
am1B (cid:1) (cid:1) (cid:1) amnB

...

...

1

C
A

(8.12)

The gradient and Hessian are given by

g(W ) =

H(W ) =

N
(cid:229)
i=1
N
(cid:229)
i=1

((cid:22) (cid:0) yi) (cid:10) xi

(8.13)

(diag((cid:22)i) (cid:0) (cid:22)i(cid:22)T

i ) (cid:10) (xixT
i )

(8.14)

where yi = (I(yi = 1); I(yi = 1); (cid:1) (cid:1) (cid:1) ; I(yi = C (cid:0) 1)) and
(cid:22)i = (p(y = 1jxi; W ); p(y = 2jxi; W ); (cid:1) (cid:1) (cid:1) ; p(y = C (cid:0)
1jxi; W )) are column vectors of length C (cid:0) 1.
Pass them to any gradient-based optimizer.

8.3.3 MAP

The new objective

8.4.1 Laplace approximation

8.4.2 Derivation of the BIC

8.4.3 Gaussian approximation for logistic

regression

8.4.4 Approximating the posterior predictive

8.4.5 Residual analysis (outlier detection) *

8.5 Online learning and stochastic

optimization

Traditionally machine learning is performed ofﬂine, how-
ever, if we have streaming data, we need to perform on-
line learning, so we can update our estimates as each new
data point arrives rather than waiting until the end (which
may never occur). And even if we have a batch of data, we
might want to treat it like a stream if it is too large to hold
in main memory. Below we discuss learning methods for
this kind of scenario.

TODO

8.5.1 The perceptron algorithm

8.5.1.1 Representation

47

Fig. 8.1: Perceptron

w   0; b   0; k   0;
while no mistakes made within the for loop do

for i   1 to N do

if yi(w (cid:1) xi + b) (cid:20) 0 then
w   w + hyixi;
b   b + hyi;
k   k + 1;

end

end

end

Algorithm 1: Perceptron learning algorithm, primal
form, using SGD

Theorem 8.1. (Novikoff) If traning data set D is linearly
separable, then
1. There exists a hyperplane denoted as bwopt (cid:1) x + bopt =

0 which can correctly seperate all samples, and

H : y = f (x) = sign(wT x + b)

{

(8.20)

where sign(x) =

+1;
(cid:0)1;

x (cid:21) 0
x < 0

, see Fig. 8.119.

2.

9g > 0; 8i; yi(wopt (cid:1) xi + bopt) (cid:21) g

(8.24)

)
2

(

R
g

k (cid:20)

; where R = max
1(cid:20)i(cid:20)N

jjbxijj

(8.25)

8.5.1.2 Evaluation

L(w; b) = (cid:0)yi(wT xi + b)
Remp( f ) = (cid:0)(cid:229)

yi(wT xi + b)

i

(8.21)
(8.22)

(8.23)

8.5.1.3 Optimization

Primal form

Convergency

19 https://en.wikipedia.org/wiki/Perceptron

Proof. (1) let g = min
yi(wopt (cid:1) xi + bopt) (cid:21) g.

i

yi(wopt (cid:1) xi + bopt), then we get

(2) The algorithm start from bx0 = 0, if a instance is
misclassiﬁed, then update the weight. Let bwk(cid:0)1 denotes
the extended weight before the k-th misclassiﬁed instance,
then we can get

yi( bwk(cid:0)1 (cid:1) bxi) = yi(wk(cid:0)1 (cid:1) xi + bk(cid:0)1) (cid:20) 0 (8.26)
(8.27)

bwk = bwk(cid:0)1 + hyi bxi

We could infer the following two equations, the proof

procedure are omitted.
1. bwk (cid:1) bwopt (cid:21) khg
2. jj bwkjj2 (cid:20) kh2R2

48

From above two equations we get

(cid:12)
(cid:12)
(cid:12) bwopt
(cid:12)

(cid:12)
(cid:12)
(cid:12) (cid:20)
(cid:12)

p

khR

khg (cid:20) bwk (cid:1) bwopt (cid:20) jj bwkjj
k2g2 (cid:20) kR2

(

)
2

R
g

i.e. k (cid:20)

Dual form

w =

b =

N
(cid:229)
i=1
N
(cid:229)
i=1

aiyixi

aiyi
(

f (x) = sign

N
(cid:229)
j=1

(8.28)

(8.29)

)

ajy jx j (cid:1) x + b

(8.30)

(cid:11)   0; b   0; k   0;
while no mistakes made within the for loop do

for i   1 to N do
(

)

if yi

N
(cid:229)
j=1

ajy jx j (cid:1) xi + b

(cid:20) 0 then

(cid:11)   (cid:11) + h;
b   b + hyi;
k   k + 1;

end

end

end

Algorithm 2: Perceptron learning algorithm, dual form

8.6 Generative vs discriminative classiﬁers

8.6.1 Pros and cons of each approach

• Easy to ﬁt? As we have seen, it is usually very easy
to ﬁt generative classiﬁers. For example, in Sections
3.5.1 and 4.2.4, we show that we can ﬁt a naive Bayes
model and an LDA model by simple counting and aver-
aging. By contrast, logistic regression requires solving
a convex optimization problem (see Section 8.2 for the
details), which is much slower.

• Fit classes separately? In a generative classiﬁer, we
estimate the parameters of each class conditional den-
sity independently, so we do not have to retrain the
model when we add more classes. In contrast, in dis-
criminative models, all the parameters interact, so the
whole model must be retrained if we add a new class.
(This is also the case if we train a generative model

to maximize a discriminative objective Salojarvi et al.
(2005).)

• Handle missing features easily? Sometimes some of
the inputs (components ofx) are not observed. In a gen-
erative classiﬁer, there is a simple method for dealing
with this, as we discuss in Section 8.6.2. However, in
a discriminative classiﬁer, there is no principled solu-
tion to this problem, since the model assumes that xis
always available to be conditioned on (although see
(Marlin 2008) for some heuristic approaches).

• Can handle unlabeled training data? There is much
interest in semi-supervised learning, which uses unla-
beled data to help solve a supervised task. This is fairly
easy to do using generative models (see e.g., (Lasserre
et al. 2006; Liang et al. 2007)), but is much harder to
do with discriminative models.

• Symmetric in inputs and outputs? We can run a gen-
erative model backwards, and infer probable inputs
given the output by computing p(xjy). This is not pos-
sible with a discriminative model. The reason is that a
generative model deﬁnes a joint distribution on x and
y, and hence treats both inputs and outputs symmetri-
cally.

• Can handle feature preprocessing? A big advantage
of discriminative methods is that they allow us to pre-
process the input in arbitrary ways, e.g., we can re-
place x with ϕ(x), which could be some basis func-
tion expansion, etc. It is often hard to deﬁne a gener-
ative model on such pre-processed data, since the new
features are correlated in complex ways.

• Well-calibrated probabilities? Some generative mod-
els, such as naive Bayes, make strong independence
assumptions which are often not valid. This can re-
sult in very extreme posterior class probabilities (very
near 0 or 1). Discriminative models, such as logistic re-
gression, are usually better calibrated in terms of their
probability estimates.

See Table 8.1 for a summary of the classiﬁcation and

regression techniques we cover in this book.

8.6.2 Dealing with missing data

Sometimes some of the inputs (components of x) are not
observed; this could be due to a sensor failure, or a fail-
ure to complete an entry in a survey, etc. This is called
the missing data problem (Little. and Rubin 1987). The
ability to handle missing data in a principled way is one
of the biggest advantages of generative models.

To formalize our assumptions, we can associate a bi-
nary response variable ri 2 f0; 1g that speciﬁes whether
each value xi is observed or not. The joint model has the

49

Model

Classif/regr Gen/Discr Param/Non Section

Classif
Discriminant analysis
Classif
Naive Bayes classiﬁer
Classif
Tree-augmented Naive Bayes classiﬁer
Regr
Linear regression
Classif
Logistic regression
Both
Sparse linear/ logistic regression
Mixture of experts
Both
Multilayer perceptron (MLP)/ Neural network Both
Conditional random ﬁeld (CRF)

Classif

K nearest neighbor classiﬁer
(Inﬁnite) Mixture Discriminant analysis
Classiﬁcation and regression trees (CART)
Boosted model
Sparse kernelized lin/logreg (SKLR)
Relevance vector machine (RVM)
Support vector machine (SVM)
Gaussian processes (GP)
Smoothing splines

Classif
Classif
Both
Both
Both
Both
Both
Both
Regr

Param
Gen
Param
Gen
Param
Gen
Discrim Param
Discrim Param
Discrim Param
Discrim Param
Discrim Param
Discrim Param

Non
Gen
Gen
Non
Discrim Non
Discrim Non
Discrim Non
Discrim Non
Discrim Non
Discrim Non
Discrim Non

Sec. 4.2.2, 4.2.4
Sec. 3.5, 3.5.1.2
Sec. 10.2.1
Sec. 1.4.5, 7.3, 7.6
Sec. 1.4.6, 8.2.1.1, 8.4.3, 21.8.1.1
Ch. 13
Sec. 11.2.4
Ch. 16
Sec. 19.6

Sec. TODO, TODO
Sec. 14.7.3
Sec. 16.2
Sec. 16.4
Sec. 14.3.2
Sec. 14.3.2
Sec. 14.5
Ch. 15
Section 15.4.6

Table 8.1: List of various models for classiﬁcation and regression which we discuss in this book. Columns are as
follows: Model name; is the model suitable for classiﬁcation, regression, or both; is the model generative or
discriminative; is the model parametric or non-parametric; list of sections in book which discuss the model. See also
http://pmtk3.googlecode.com/svn/trunk/docs/tutorial/html/tutSupervised.html for
the PMTK equivalents of these models. Any generative probabilistic model (e.g., HMMs, Boltzmann machines,
Bayesian networks, etc.) can be turned into a classiﬁer by using it as a class conditional density

form p(xi; rij(cid:18); ϕ) = p(rijxi; ϕ)p(xij(cid:18)), where ϕ are the
parameters controlling whether the item is observed or
not.

•

•

•

i ; ϕ), where xo

If we assume p(rijxi; ϕ) = p(rijϕ), we say the data is
missing completely at random or MCAR.
If we assume p(rijxi; ϕ) = p(rijxo
i is the
observed part of xi, we say the data is missing at ran-
dom or MAR.
If neither of these assumptions hold, we say the data
is not missing at random or NMAR. In this case, we
have to model the missing data mechanism, since the
pattern of missingness is informative about the values
of the missing data and the corresponding parameters.
This is the case in most collaborative ﬁltering prob-
lems, for example.

See e.g., (Marlin 2008) for further discussion. We will

henceforth assume the data is MAR.

When dealing with missing data, it is helpful to distin-
guish the cases when there is missingness only at test time
(so the training data is complete data), from the harder
case when there is missingness also at training time. We
will discuss these two cases below. Note that the class la-
bel is always missing at test time, by deﬁnition; if the class
label is also sometimes missing at training time, the prob-
lem is called semi-supervised learning.

8.6.2.1 Missing data at test time

In a generative classiﬁer, we can handle features that are
MAR by marginalizing them out. For example, if we are
missing the value ofx1, we can compute

p(y = cjx2:D; (cid:18)) (cid:181) p(y = cj(cid:18))p(x2:Djy = c; (cid:18))

=(cid:181) p(y = cj(cid:18))(cid:229)
x1

(8.31)
p(x1; x2:Djy = c; (cid:18))

(8.32)

Similarly, in discriminant analysis, no matter what reg-
ularization method was used to estimate the parameters,
we can always analytically marginalize out the missing
variables (see Section 4.3):

p(x2:Djy = c; (cid:18)) = N (x2:Dj(cid:22)c;2:D; (cid:6)c;2:D)

(8.33)

8.6.2.2 Missing data at training time

Missing data at training time is harder to deal with. In par-
ticular, computing the MLE or MAP estimate is no longer
a simple optimization problem, for reasons discussed in
Section TODO. However, soon we will study are a variety
of more sophisticated algorithms (such as EM algorithm,
in Section 11.4) for ﬁnding approximate ML or MAP es-
timates in such cases.

50

8.6.3 Fishers linear discriminant analysis

(FLDA) *

TODO

Chapter 9
Generalized linear models and the exponential family

9.1 The exponential family

Equation 9.2 can be generalized by writing

Before deﬁning the exponential family, we mention sev-
eral reasons why it is important:

•

It can be shown that, under certain regularity condi-
tions, the exponential family is the only family of dis-
tributions with ﬁnite-sized sufﬁcient statistics, mean-
ing that we can compress the data into a ﬁxed-sized
summary without loss of information. This is particu-
larly useful for online learning, as we will see later.
• The exponential family is the only family of distribu-
tions for which conjugate priors exist, which simpliﬁes
the computation of the posterior (see Section 9.1.5).
• The exponential family can be shown to be the family
of distributions that makes the least set of assumptions
subject to some user-chosen constraints (see Section
9.1.6).

• The exponential family is at the core of generalized lin-

ear models, as discussed in Section 9.2.

• The exponential family is at the core of variational in-

ference, as discussed in Section TODO.

9.1.1 Deﬁnition

A pdf or pmf p(xj(cid:18)),for x 2 Rm and (cid:18) 2 RD, is said to be
in the exponential family if it is of the form

p(xj(cid:18)) =

1
Z((cid:18))

h(x) exp[(cid:18)T ϕ(x)]

= h(x) exp[(cid:18)T ϕ(x) (cid:0) A((cid:18))]

where

∫

Z((cid:18)) =

h(x) exp[(cid:18)T ϕ(x)]dx

A((cid:18)) = log Z((cid:18))

(9.1)

(9.2)

(9.3)

(9.4)

Here (cid:18) are called the natural parameters or canoni-
cal parameters, ϕ(x) 2 RD is called a vector of sufﬁcient
statistics, Z((cid:18)) is called the partition function, A((cid:18)) is
called the log partition function or cumulant function,
and h(x) is the a scaling constant, often 1. If ϕ(x) = x,
we say it is a natural exponential family.

p(xj(cid:18)) = h(x) exp[h((cid:18))T ϕ(x) (cid:0) A(h((cid:18)))]

(9.5)

where h is a function that maps the parameters (cid:18) to the
canonical parameters (cid:17) = h((cid:18)).If dim((cid:18)) < dim(h((cid:18))),
it is called a curved exponential family, which means we
have more sufﬁcient statistics than parameters. If h((cid:18)) =
(cid:18), the model is said to be in canonical form. We will
assume models are in canonical form unless we state oth-
erwise.

9.1.2 Examples

9.1.2.1 Bernoulli

The Bernoulli for x 2 f0; 1g can be written in exponential
family form as follows:

Ber(xjm) = mx(1 (cid:0) m)1(cid:0)x

= exp[x log m+ (1 (cid:0) x) log(1 (cid:0) m)]

(9.6)

where ϕ(x) = (I(x = 0); I(x = 1)) and (cid:18) = (log m; log(1 (cid:0)
m)).

However, this representation is over-complete since
1T ϕ(x) = I(x = 0) + I(x = 1) = 1. Consequently (cid:18) is not
uniquely identiﬁable. It is common to require that the rep-
resentation be minimal, which means there is a unique q
associated with the distribution. In this case, we can just
deﬁne

Ber(xjm) = (1 (cid:0) m) exp

x log

(9.7)

(

)

m
1 (cid:0) m
1
1 (cid:0) m

m
1 (cid:0) m; Z =

where ϕ(x) = x; q = log

We can recover the mean parameter m from the canon-

ical parameter using

m = sigm(q) =

1
1 + e(cid:0)q

(9.8)

51

52

9.1.2.2 Multinoulli

We can represent the multinoulli as a minimal exponential
family as follows:

K
(cid:213)
k=1

= exp

(

K
(cid:229)
k=1

)

xk log mk

xk log mk + (1 (cid:0)

K(cid:0)1
(cid:229)
k=1

xk) log(1 (cid:0)

K(cid:0)1
(cid:229)
k=1

]

mk)
]

xk log

mk
1 (cid:0) (cid:229)K(cid:0)1
k=1

mk

+ log(1 (cid:0)
]

K(cid:0)1
(cid:229)
k=1

mk)

xk log

mk
mK

+ log mK

, where mK ≜ 1 (cid:0)

K(cid:0)1
(cid:229)
k=1

mk

Cat(xj(cid:22)) =

[

[

[

K(cid:0)1
(cid:229)
k=1
K(cid:0)1
(cid:229)
k=1
K(cid:0)1
(cid:229)
k=1

= exp

= exp

= exp

(cid:18) = (

m

s2 ; (cid:0) 1

2s2 )

ϕ(x) = (x; x2)

Z((cid:18)) =

p

2psexp(

m2
2s2 )

(9.16)

(9.17)

(9.18)

9.1.2.4 Non-examples

Not all distributions of interest belong to the exponen-
tial family. For example, the uniform distribution,X (cid:24)
U(a; b), does not, since the support of the distribution de-
pends on the parameters. Also, the Student T distribution
(Section TODO) does not belong, since it does not have
the required form.

We can write this in exponential family form as fol-

lows:

9.1.3 Log partition function

Cat(xj(cid:22)) = exp[(cid:18)T ϕ(x) (cid:0) A((cid:18))]
mK(cid:0)1
mK

(cid:18) ≜ (log

; (cid:1) (cid:1) (cid:1) ; log

m1
mK

ϕ(x) ≜ (x1; (cid:1) (cid:1) (cid:1) ; xK(cid:0)1)

)

(9.9)

(9.10)

(9.11)

We can recover the mean parameters from the canoni-

cal parameters using

An important property of the exponential family is that
derivatives of the log partition function can be used to
generate cumulants of the sufﬁcient statistics.20 For this
reason, A((cid:18)) is sometimes called a cumulant function.
We will prove this for a 1-parameter distribution; this can
be generalized to a K-parameter distribution in a straight-
forward way. For the ﬁrst derivative we have

mk =

mK = 1 (cid:0)

eqk
1 + (cid:229)K(cid:0)1
j=1 eqj
(cid:229)K(cid:0)1
j=1 eqj
1 + (cid:229)K(cid:0)1
j=1 eqj

=

1
j=1 eqj

1 + (cid:229)K(cid:0)1

and hence

A((cid:18)] = (cid:0) log mK = log(1 +

K(cid:0)1
(cid:229)
j=1

eqj )

(9.12)

(9.13)

(9.14)

9.1.2.3 Univariate Gaussian

The univariate Gaussian can be written in exponential
family form as follows:

]

[
(cid:0) 1
2s2 (x (cid:0) m)2
[
m
(cid:0) 1
2s2 x2 +

s2 x (cid:0) 1
2s2

]

m2

N (xjm; s2) =

1p

2ps

exp

exp

1p

2ps
1
Z((cid:18))

exp[(cid:18)T ϕ(x)]

=

=

where

For the second derivative we have
{

∫

}

log

exp [qϕ(x)] h(x)dx

dA
dq =

d
dq
d
dq
∫

∫

=

=

=

=

∫

∫

∫

exp [qϕ(x)] h(x)dx
exp [qϕ(x)] h(x)dx
ϕ(x)exp [qϕ(x)] h(x)dx
exp(A(q))

ϕ(x) exp [qϕ(x) (cid:0) A(q)] h(x)dx

ϕ(x)p(x)dx = E[ϕ(x)]

(9.19)

For the second derivative we have

d2A
dq2 =
=

∫

∫

∫

ϕ(x) exp [qϕ(x) (cid:0) A(q)] h(x)

ϕ(x)p(x)

]
[
ϕ(x) (cid:0) A′(q)
∫

dx

]
[
ϕ(x) (cid:0) A′(q)

dx

=

ϕ2(x)p(x)dx (cid:0) A′(q)

ϕ(x)p(x)dx

= E[ϕ2(x)] (cid:0) E[ϕ(x)]2 = var[ϕ(x)]

(9.20)

(9.15)

In the multivariate case, we have that

20 The ﬁrst and second cumulants of a distribution are its mean E[X]
and variance var[X], whereas the ﬁrst and second moments are its
mean E[X] and E[X 2].

¶2A
¶qi¶qj

and hence

= E[ϕi(x)ϕj(x)] (cid:0) E[ϕi(x)]E[ϕj(x)]

(9.21)

(cid:209)2A((cid:18)) = cov[ϕ(x)]

(9.22)

low. We focus on scalar outputs for notational simplicity.
(This excludes multinomial logistic regression, but this is
just to simplify the presentation.)

53

Since the covariance is positive deﬁnite, we see that

A((cid:18)) is a convex function (see Section A.1).

9.2.1 Basics

9.1.4 MLE for the exponential family

9.3 Probit regression

9.4 Multi-task learning

The likelihood of an exponential family model has the
form

p(Dj(cid:18)) =

[
N
(cid:213)
i=1

]

[

(

)]

h(xi)

g((cid:18))N exp

(cid:18)T

N
(cid:229)
i=1

ϕ(xi)

(9.23)

We see that the sufﬁcient statistics are N and

ϕ(D) =

N
(cid:229)
i=1

ϕ(xi) = (

N
(cid:229)
i=1

ϕ1(xi); (cid:1) (cid:1) (cid:1) ;

N
(cid:229)
i=1

ϕK(xi)) (9.24)

The Pitman-Koopman-Darmois theorem states that,
under certain regularity conditions, the exponential fam-
ily is the only family of distributions with ﬁnite sufﬁcient
statistics. (Here, ﬁnite means of a size independent of the
size of the data set.)

One of the conditions required in this theorem is that
the support of the distribution not be dependent on the
parameter.

9.1.5 Bayes for the exponential family

TODO

9.1.5.1 Likelihood

9.1.6 Maximum entropy derivation of the

exponential family *

9.2 Generalized linear models (GLMs)

Linear and logistic regression are examples of general-
ized linear models, or GLMs (McCullagh and Nelder
1989). These are models in which the output density is
in the exponential family (Section 9.1), and in which the
mean parameters are a linear combination of the inputs,
passed through a possibly nonlinear function, such as the
logistic function. We describe GLMs in more detail be-

Chapter 10
Directed graphical models (Bayes nets)

10.1 Introduction

10.1.1 Chain rule

p(x1:V ) = p(x1)p(x2jx1)p(x3jx1:2) (cid:1) (cid:1) (cid:1) p(xNjx1:V (cid:0)1)

(10.1)

10.1.2 Conditional independence

X and Y are conditionally independent given Z, denoted
X ? Y jZ, iff the conditional joint can be written as a prod-
uct of conditional marginals, i.e.

X ? Y jZ () p(X;Y jZ) = p(XjZ)p(Y jZ)

(10.2)

ﬁrst order Markov assumption: the future is indepen-

dent of the past given the present,

xt+1 ? x1:t(cid:0)1jxt

(10.3)

ﬁrst-order Markov chain

p(x1:V ) = p(x1)

V
(cid:213)
t=2

p(xt jxt(cid:0)1)

(10.4)

10.1.3 Graphical models

A graphical model(GM) is a way to represent a joint
distribution by making CI assumptions. In particular, the
nodes in the graph represent random variables, and the
(lack of) edges represent CI assumptions.

There are several kinds of graphical model, depend-
ing on whether the graph is directed, undirected, or some
combination of directed and undirected. In this chapter,
we just study directed graphs. We consider undirected
graphs in Chapter 19.

10.1.4 Directed graphical model

A directed graphical modelor DGM is a GM whose
graph is a DAG. These are more commonly known as
Bayesian networks. However, there is nothing inherently
Bayesian about Bayesian networks: they are just a way of
deﬁning probability distributions. These models are also
called belief networks. The term belief here refers to sub-
jective probability. Once again, there is nothing inherently
subjective about the kinds of probability distributions rep-
resented by DGMs.

Ordered Markov property

xs ? xpred(s) pa(s) ? xpa(s)

(10.5)

where pa(s) are the parents of nodes, and pred(s) are the
predecessors of nodes in the DAG.
Markov chain on a DGM

p(x1:V jG) =

V
(cid:213)
t=1

p(xt jxpa(t))

(10.6)

Fig. 10.1: (a) A simple DAG on 5 nodes, numbered in
topological order. Node 1 is the root, nodes 4 and 5 are
the leaves. (b) A simple undirected graph, with the
following maximal cliques: 1,2,3, 2,3,4, 3,5.

55

56

10.2 Examples

10.2.1 Naive Bayes classiﬁers

p(xhjxv; q) =

p(xh; xvj(cid:18))
p(xvj(cid:18))

=

p(xh; xvj(cid:18))
p(x′

h; xvj(cid:18))

(cid:229)x′

h

(10.7)

Sometimes only some of the hidden variables are of
interest to us. So let us partition the hidden variables into
query variables, xq, whose value we wish to know, and
the remaining nuisance variables, xn, which we are not
interested in. We can compute what we are interested in
by marginalizing out the nuisance variables:
p(xqjxv; (cid:18)) = (cid:229)
xn

p(xq; xnjxv; (cid:18))

(10.8)

Fig. 10.2: (a) A naive Bayes classiﬁer represented as a
DGM. We assume there are D = 4 features, for
simplicity. Shaded nodes are observed, unshaded nodes
are hidden. (b) Tree-augmented naive Bayes classiﬁer for
D = 4 features. In general, the tree topology can change
depending on the value of y.

10.4 Learning

MAP estimate:

ˆ(cid:18) = arg max

(cid:18)

N
(cid:229)
i=1

log p(xi;vj(cid:18)) + log p((cid:18))

(10.9)

10.2.2 Markov and hidden Markov models

Fig. 10.3: A ﬁrst and second order Markov chain.

Fig. 10.4: A ﬁrst-order HMM.

10.4.1 Learning from complete data

If all the variables are fully observed in each case, so there
is no missing data and there are no hidden variables, we
say the data is complete. For a DGM with complete data,
the likelihood is given by

p(Dj(cid:18)) =

=

=

N
(cid:213)
i=1
N
(cid:213)
i=1
V
(cid:213)
t=1

p(xij(cid:18))

V
(cid:213)
t=1

p(xitjxi;pa(t); (cid:18)t )

(10.10)

p(Dt j(cid:18)t )

where Dt is the data associated with node t and its parents,
i.e., the t’th family.

Now suppose that the prior factorizes as well:

p((cid:18)) =

V
(cid:213)
t=1

p((cid:18)t )

(10.11)

10.3 Inference

Then clearly the posterior also factorizes:

Suppose we have a set of correlated random variables with
joint distribution p(x1:V j(cid:18)). Let us partition this vector
into the visible variables xv, which are observed, and the
hidden variables, xh, which are unobserved. Inference
refers to computing the posterior distribution of the un-
knowns given the knowns:

p((cid:18)jD) (cid:181) p(Dj(cid:18))p((cid:18)) =

V
(cid:213)
t=1

p(Dtj(cid:18)t)p((cid:18)t )

(10.12)

10.4.2 Learning with missing and/or latent

then from ?? and 10.17:

variables

If we have missing data and/or hidden variables, the like-
lihood no longer factorizes, and indeed it is no longer con-
vex, as we explain in detail in Section TODO. This means
we will usually can only compute a locally optimal ML
or MAP estimate. Bayesian inference of the parameters
is even harder. We discuss suitable approximate inference
techniques in later chapters.

57

(10.18)

qynvck
vck

p(xjG; q) =

V
(cid:213)
v=1

Cv(cid:213)

c=1

K
(cid:213)
k=1

qyvck
vck

Likelihood

p(DjG; q) =

N
(cid:213)
n=1

p(xnjG; q) =

N
(cid:213)
n=1

V
(cid:213)
v=1

Cnv(cid:213)

c=1

K
(cid:213)
k=1

(10.19)
where ynv = f (pa(xnv)), f(x) is a map from x to a vector,
there is only one element in the vector is 1.

10.5 Conditional independence properties of

DGMs

10.6 Inﬂuence (decision) diagrams *

10.5.1 d-separation and the Bayes Ball

algorithm (global Markov properties)

1. P contains a chain

p(x; zjy) =

p(x; y; z)
p(y)

=

p(x)p(yjx)p(zjy)
p(y)

=

p(x; y)p(zjy)
p(y)

= p(xjy)p(zjy)

(10.13)

2. P contains a fork

p(x; zjy) =

p(x; y; z)
p(y)

=

p(y)p(xjy)p(zjy)
p(y)

3. P contains v-structure

p(x; zjy) =

p(x; y; z)
p(y)

=

p(x)p(z)p(yjx; z)
p(y)

= p(xjy)p(zjy)

(10.14)

̸= p(xjy)p(zjy)

(10.15)

10.5.2 Other Markov properties of DGMs

10.5.3 Markov blanket and full conditionals

mb(t) = ch(t) [ pa(t) [ copa(t)

(10.16)

10.5.4 Multinoulli Learning

Multinoulli Distribution

Cat(xjm) =

K
(cid:213)
k=1

mxk
k

(10.17)

Chapter 11
Mixture models and the EM algorithm

11.1 Latent variable models

11.2 Mixture models

In Chapter 10 we showed how graphical models can be
used to deﬁne high-dimensional joint probability distri-
butions. The basic idea is to model dependence between
two variables by adding an edge between them in the
graph. (Technically the graph represents conditional in-
dependence, but you get the point.)

An alternative approach is to assume that the observed
variables are correlated because they arise from a hid-
den common cause. Model with hidden variables are also
known as latent variable models or LVMs. As we will
see in this chapter, such models are harder to ﬁt than mod-
els with no latent variables. However, they can have sig-
niﬁcant advantages, for two main reasons.

• First, LVMs often have fewer parameters than models
that directly represent correlation in the visible space.
• Second, the hidden variables in an LVM can serve as a
bottleneck, which computes a compressed representa-
tion of the data. This forms the basis of unsupervised
learning, as we will see. Figure 11.1 illustrates some
generic LVM structures that can be used for this pur-
pose.

The simplest form of LVM is when zi 2 f1; (cid:1) (cid:1) (cid:1) ; Kg, rep-
resenting a discrete latent state. We will use a discrete
prior for this, p(zi) = Cat(p). For the likelihood, we use
p(xijzi = k) = pk(xi), where pk is the k’th base distri-
bution for the observations; this can be of any type. The
overall model is known as a mixture model, since we are
mixing together the K base distributions as follows:

p(xij(cid:18)) =

K
(cid:229)
k=1

pk pk(xij(cid:18))

(11.1)

Depending on the form of the likelihood p(xijzi) and
the prior p(zi), we can generate a variety of different
models, as summarized in Table 11.1.

p(xijzi)

p(zi)

Name

Section

MVN
Discrete
Prod. Discrete Discrete

Prod. Gaussian Prod. Gaussian

Prod. Gaussian Prod. Laplace

Mixture of Gaussians
11.2.1
Mixture of multinomials 11.2.2
Factor analysis/
probabilistic PCA
Probabilistic ICA/
sparse coding

12.1.5

12.6

Prod. Discrete

Prod. Gaussian Multinomial PCA

Prod. Discrete Dirichlet

Latent Dirichlet
allocation

Prod. Noisy-OR Prod. Bernoulli BN20/ QMR
Prod. Bernoulli Prod. Bernoulli Sigmoid belief net

27.2.3

27.3

10.2.3
27.7

Table 11.1: Summary of some popular directed latent
variable models. Here Prod means product, so Prod.
Discrete in the likelihood means a factored distribution of
the form (cid:213) j Cat(xi jjzi), and Prod. Gaussian means a
factored distribution of the form (cid:213) j N (xi jjzi).

Fig. 11.1: A latent variable model represented as a DGM.
(a) Many-to-many. (b) One-to-many. (c) Many-to-one.
(d) One-to-one.

11.2.1 Mixtures of Gaussians

pk(xij(cid:18)) = N (xij(cid:22)k; Sk)

(11.2)

59

60

11.2.2 Mixtures of multinoullis

11.2.4 Mixtures of experts

pk(xij(cid:18)) =

D
(cid:213)
j=1

Ber(xi jjmjk) =

D
(cid:213)
j=1

mxi j
jk (1 (cid:0) mjk)1(cid:0)xi j

(11.3)
where mjk is the probability that bit j turns on in cluster k.
The latent variables do not have to any meaning, we
might simply introduce latent variables in order to make
the model more powerful. For example, one can show that
the mean and covariance of the mixture distribution are
given by

Section 14.7.3 TODO described how to use mixture mod-
els in the context of generative classiﬁers. We can also
use them to create discriminative models for classiﬁcation
and regression. For example, consider the data in Figure
11.2(a). It seems like a good model would be three differ-
ent linear regression functions, each applying to a differ-
ent part of the input space. We can model this by allowing
the mixing weights and the mixture densities to be input-
dependent:

E[x] =

Cov[x] =

K
(cid:229)
k=1
K
(cid:229)
k=1

pk(cid:22)k

(11.4)

pk(Sk + (cid:22)k(cid:22)T

k ) (cid:0) E[x]E[x]T

(11.5)

where Sk = diag(mjk(1 (cid:0) mjk)). So although the compo-
nent distributions are factorized, the joint distribution is
not. Thus the mixture distribution can capture correlations
between variables, unlike a single product-of-Bernoullis
model.

11.2.3 Using mixture models for clustering

There are two main applications of mixture models, black-
box density model(see Section 14.7.3 TODO) and cluster-
ing(see Chapter 25 TODO).

Soft clustering

p(yijxi; zi = k; (cid:18)) = N (yijwT

k x; s2
k )
p(zijxi; (cid:18)) = Cat(zijS(V T xi))

(11.8)

(11.9)

See Figure 11.3(a) for the DGM.
This model is called a mixture of experts or MoE (Jor-
dan and Jacobs 1994). The idea is that each submodel is
considered to be an expert in a certain region of input
space. The function p(zijxi; (cid:18)) is called a gating func-
tion, and decides which expert to use, depending on the
input values. For example, Figure 11.2(b) shows how the
three experts have carved up the 1d input space, Figure
11.2(a) shows the predictions of each expert individually
(in this case, the experts are just linear regression mod-
els), and Figure 11.2(c) shows the overall prediction of
the model, obtained using

K
(cid:229)
k=1

p(yijxi; (cid:18)) =

p(zi = kjxi; (cid:18))p(yijxi; zi = k; (cid:18))

(11.10)
We discuss how to ﬁt this model in Section TODO

rik ≜ p(zi = kjxi; (cid:18)) =

p(zi = k; xij(cid:18))
p(xij(cid:18))
p(zi = kj(cid:18))p(xijzi = k; (cid:18))
k′=1 p(zi = k′j(cid:18))p(xijzi = k′; (cid:18))
(cid:229)K

=

11.4.3.

(11.6)

where rik is known as the responsibility of cluster k for
point i.

Hard clustering

11.3 Parameter estimation for mixture

models

11.3.1 Unidentiﬁability

z(cid:3)
i

≜ arg max

k

rik = arg max

k

p(zi = kjxi; (cid:18))

(11.7)

11.3.2 Computing a MAP estimate is

The difference between generative classiﬁers and mix-
ture models only arises at training time: in the mixture
case, we never observe zi, whereas with a generative clas-
siﬁer, we do observe yi(which plays the role of zi).

non-convex

11.4 The EM algorithm

11.4.1 Introduction

For many models in machine learning and statistics, com-
puting the ML or MAP parameter estimate is easy pro-
vided we observe all the values of all the relevant random

61

Fig. 11.3: (a) A mixture of experts. (b) A hierarchical
mixture of experts.

variables, i.e., if we have complete data. However, if we
have missing data and/or latent variables, then computing
the ML/MAP estimate becomes hard.

One approach is to use a generic gradient-based op-
timizer to ﬁnd a local minimum of the NLL((cid:18)). How-
ever, we often have to enforce constraints, such as the fact
that covariance matrices must be positive deﬁnite, mix-
ing weights must sum to one, etc., which can be tricky.
In such cases, it is often much simpler (but not always
faster) to use an algorithm called expectation maximiza-
tion,or EM for short (Dempster et al. 1977; Meng and van
Dyk 1997; McLachlan and Krishnan 1997). This is is an
efﬁcient iterative algorithm to compute the ML or MAP
estimate in the presence of missing or hidden data, often
with closed-form updates at each step. Furthermore, the
algorithm automatically enforce the required constraints.
See Table 11.2 for a summary of the applications of

EM in this book.

Table 11.2: Some models discussed in this book for
which EM can be easily applied to ﬁnd the ML/ MAP
parameter estimate.

Model

Section

Mix. Gaussians
Mix. experts
Factor analysis
Student T
Probit regression
DGM with hidden variables
MVN with missing data
HMMs
Shrinkage estimates of Gaussian means Exercise 11.13

11.4.2
11.4.3
12.1.5
11.4.5
11.4.6
11.4.4
11.6.1
17.5.2

(a)

(b)

(c)

Fig. 11.2: (a) Some data ﬁt with three separate regression
lines. (b) Gating functions for three different experts. (c)
The conditionally weighted average of the three expert
predictions.

62

11.4.2 Basic idea

EM exploits the fact that if the data were fully observed,
then the ML/ MAP estimate would be easy to compute. In
particular, each iteration of the EM algorithm consists of
two processes: The E-step, and the M-step.

•

•

In the E-step, the missing data are inferred given the
observed data and current estimate of the model pa-
rameters. This is achieved using the conditional expec-
tation, explaining the choice of terminology.
In the M-step, the likelihood function is maximized
under the assumption that the missing data are known.
The missing data inferred from the E-step are used in
lieu of the actual missing data.

Let xi be the visible or observed variables in case i,
and let zi be the hidden or missing variables. The goal is
to maximize the log likelihood of the observed data:

In summary, the EM algorithm’s pseudo code is as fol-

lows

input : observed data D = fx1; x2; (cid:1) (cid:1) (cid:1) ; xN g,joint distribution

P(x; zj(cid:18))

output: model’s parameters (cid:18)
// 1. identify hidden variables z, write out the log likelihood
function ℓ(x; zj(cid:18))
(cid:18)(0) = ... // initialize
while (!convergency) do

[

// 2. E-step: plug in P(x; zj(cid:18)), derive the formula of
Q((cid:18); (cid:18)t(cid:0)1)
Q((cid:18); (cid:18)t(cid:0)1) = E
ℓc((cid:18))jD; qt(cid:0)1
// 3. M-step: ﬁnd (cid:18) that maximizes the value of
Q((cid:18); (cid:18)t(cid:0)1)
(cid:18)t = arg max

Q((cid:18); (cid:18)t(cid:0)1)

]

(cid:18)

end

Algorithm 3: EM algorithm

p(xi; zij(cid:18))

Below we explain how to perform the E and M steps
for several simple models, that should make things clearer.

ℓ((cid:18)) = log p(Dj(cid:18)) =

N
(cid:229)
i=1

log p(xij(cid:18)) =

N
(cid:229)
i=1

log(cid:229)
zi

(11.11)
Unfortunately this is hard to optimize, since the log

cannot be pushed inside the sum.

EM gets around this problem as follows. Deﬁne the

complete data log likelihood to be

ℓc((cid:18)) =

N
(cid:229)
i=1

log p(xi; zij(cid:18))

(11.12)

This cannot be computed, since zi is unknown. So let
us deﬁne the expected complete data log likelihood as
follows:

Q((cid:18); (cid:18)t(cid:0)1) ≜ E

zjD;qt(cid:0)1 [ℓc((cid:18))] = E

[
ℓc((cid:18))jD; qt(cid:0)1

]

(11.13)
where t is the current iteration number. Q is called the
auxiliary function(see Section 11.4.9 for derivation). The
expectation is taken wrt the old parameters, (cid:18)t(cid:0)1, and the
observed data D. The goal of the E-step is to compute
Q((cid:18); (cid:18)t(cid:0)1), or rather, the parameters inside of it which
the MLE(or MAP) depends on; these are known as the
expected sufﬁcient statistics or ESS. In the M-step, we
optimize the Q function wrt (cid:18):

(cid:18)t = arg max

(cid:18)

Q((cid:18); (cid:18)t(cid:0)1)

(11.14)

To perform MAP estimation, we modify the M-step as

follows:

11.4.3 EM for GMMs

11.4.3.1 Auxiliary function

Q((cid:18); (cid:18)t(cid:0)1) = E

zjD;qt(cid:0)1 [ℓc((cid:18))]
[

]

= E

zjD;qt(cid:0)1

N
(cid:229)
log p(xi; zij(cid:18))
i=1
{

[

]}

=

=

=

=

N
(cid:229)
i=1

N
(cid:229)
i=1
N
(cid:229)
i=1
N
(cid:229)
i=1

E

zjD;qt(cid:0)1

log

K
(cid:213)
k=1

(pk p(xij(cid:18)k))

I(zi=k)

K
(cid:229)
k=1
K
(cid:229)
k=1
K
(cid:229)
k=1

E[I(zi = k)] log [pk p(xij(cid:18)k)]

p(zi = kjxi; (cid:18)t(cid:0)1) log [pk p(xij(cid:18)k)]

rik log pk +

N
(cid:229)
i=1

K
(cid:229)
k=1

rik log p(xij(cid:18)k)

(11.16)

where rik ≜ E[I(zi = k)] = p(zi = kjxi; (cid:18)t(cid:0)1) is the re-
sponsibility that cluster k takes for data point i. This is
computed in the E-step, described below.

(cid:18)t = arg max

(cid:18)

Q((cid:18); (cid:18)t(cid:0)1) + log p((cid:18))

(11.15)

11.4.3.2 E-step

The E step remains unchanged.

The E-step has the following simple form, which is the
same for any mixture model:

11.4.3.4 Algorithm pseudo code

(11.17)

63

rik = p(zi = kjxi; (cid:18)t(cid:0)1) =

p(zi = k; xij(cid:18)t(cid:0)1)
p(xij(cid:18)t(cid:0)1)

=

pk p(xij(cid:18)t(cid:0)1
k′=1

pk′ p(xij(cid:18)t(cid:0)1

)

k

k

(cid:229)K

)

11.4.3.3 M-step

In the M-step, we optimize Q wrt (cid:25) and (cid:18)k.

For (cid:25), grouping together only the terms that depend
rik log pk.

on pk, we ﬁnd that we need to maximize

K
(cid:229)
k=1
pk = 1, since

N
(cid:229)
i=1
K
(cid:229)
k=1

However, there is an additional constraint

they represent the probabilities (cid:25)k = P(zi = k). To deal
with the constraint we construct the Lagrangian

L((cid:25)) =

N
(cid:229)
i=1

K
(cid:229)
k=1

rik log pk + b

)

pk (cid:0) 1

(

K
(cid:229)
k=1

end

where b is the Lagrange multiplier. Taking derivatives, we
ﬁnd

input : observed data D = fx1; x2; (cid:1) (cid:1) (cid:1) ; xN g,GMM
output: GMM’s parameters (cid:25); (cid:22); (cid:6)
// 1. initialize
(cid:25)(0) = ...
(cid:22)(0) = ...
(cid:6)(0) = ...
t = 0
while (!convergency) do

)

// 2. E-step

k

k

(cid:229)K

(cid:229)N

ˆrik =

pk p(xij(cid:18)t(cid:0)1
)
;(cid:6)t(cid:0)1
k′ p(xij(cid:22)t(cid:0)1
p
k′=1
k
// 3. M-step
i=1 ˆrik
ˆ(cid:25)k =
N
(cid:229)N
i=1 ˆrikxi
ˆ(cid:22)k =
(cid:229)N
i=1 ˆrik
(cid:229)N
i=1 ˆrikxixT
i
(cid:229)N
i=1 ˆrik

(cid:0) (cid:22)k(cid:22)T
k

ˆ(cid:6)k =
++t

Algorithm 4: EM algorithm for GMM

ˆrik

N
(cid:229)
i=1
N

ˆ(cid:25)k =

(11.18)

11.4.3.5 MAP estimation

This is the same for any mixture model, whereas (cid:18)k de-
pends on the form of p(xj(cid:18)k).

For (cid:18)k, plug in the pdf to Equation 11.16

Q((cid:18); (cid:18)t(cid:0)1) =

K
(cid:229)
k=1

N
(cid:229)
i=1
(xi (cid:0) (cid:22)k)T (cid:6)(cid:0)1

K
rik log pk (cid:0) 1
(cid:229)
2
k=1
]
k (xi (cid:0) (cid:22)k)

N
(cid:229)
i=1

rik [log j(cid:6)kj+

Take partial derivatives of Q wrt (cid:22)k, (cid:6)k and let them

equal to 0, we can get

¶Q
¶(cid:22)k

= (cid:0) 1
2

N
(cid:229)
i=1

rik

[
((cid:6)(cid:0)1

k + (cid:6)(cid:0)T

k

]
)(xi (cid:0) (cid:22)k)

[
(cid:6)(cid:0)1

]
k (xi (cid:0) (cid:22)k)

= (cid:0)

rik

N
(cid:229)
i=1
(cid:229)N
i=1 ˆrikxi
(cid:229)N
i=1 ˆrik

ˆ(cid:22)k =

= 0 )

(11.19)

As usual, the MLE may overﬁt. The overﬁtting problem is
particularly severe in the case of GMMs. An easy solution
to this is to perform MAP estimation. The new auxiliary
function is the expected complete data log-likelihood plus
the log prior:

Q((cid:18); (cid:18)t(cid:0)1) =

N
(cid:229)
i=1

K
(cid:229)
k=1

rik log pk +

N
(cid:229)
i=1

K
(cid:229)
k=1

rik log p(xij(cid:18)k)

+ log p((cid:25)) +

K
(cid:229)
k=1

log p((cid:18)k)

(11.22)

It is natural to use conjugate priors.

p((cid:25)) = Dir((cid:25)j(cid:11))

p((cid:22)k; (cid:6)k) = NIW((cid:22)k; (cid:6)kjm0; k0; n0; S0)

From Equation 3.28 and Section 4.6.3, the MAP esti-

mate is given by

(xi (cid:0) (cid:22)k)(xi (cid:0) (cid:22)k)T

]

= 0 )

[

¶Q
¶(cid:6)k

N
(cid:229)
i=1

rik

1
(cid:6)k

(cid:0) 1
(cid:6)2
k

= (cid:0) 1
2
i=1 ˆrik(xi (cid:0) (cid:22)k)(xi (cid:0) (cid:22)k)T
(cid:229)N
i=1 ˆrik

ˆ(cid:6)k =

(cid:229)N

(cid:229)N
i=1 ˆrikxixT
i
(cid:229)N
i=1 ˆrik

=

(cid:0) (cid:22)k(cid:22)T
k

(11.20)

(11.21)

(11.23)

(11.24)

64

ˆpk =

ˆ(cid:22)k =

ˆ(cid:6)k =

i=1 rik + ak (cid:0) 1
(cid:229)N
ak (cid:0) K
N + (cid:229)K
k=1
i=1 rikxi + k0m0
(cid:229)N
i=1 rik + k0
(cid:229)N
k0rk
k0+rk
n0 + rk + D + 2

S0 + Sk +

where rk ≜

rik; ¯xk ≜

N
(cid:229)
i=1
N
(cid:229)
i=1

Sk ≜

rik(xi (cid:0) ¯xk)(xi (cid:0) ¯xk)T

( ¯xk (cid:0) m0)( ¯xk (cid:0) m0)T

(11.25)

(cid:229)N

i=1 rikxi
rk

;

11.4.4 EM for K-means

11.4.4.1 Representation

y j = k if ∥x j (cid:0) (cid:22)k∥2

2 is minimal

where (cid:22)k is the centroid of cluster k.

11.4.4.2 Evaluation

arg min
(cid:22)

N
(cid:229)
j=1

K
(cid:229)
k=1

gjk∥x j (cid:0) (cid:22)k∥2
2

1. K-means++.

The intuition that spreading out the k initial cluster cen-
ters is a good thing is behind this approach: the ﬁrst
cluster center is chosen uniformly at random from the
data points that are being clustered, after which each
subsequent cluster center is chosen from the remaining
data points with probability proportional to its squared
distance from the point’s closest existing cluster cen-
ter21.
The exact algorithm is as follows:

a. Choose one center uniformly at random from

among the data points.

b. For each data point x, compute D(x), the distance
between x and the nearest center that has already
been chosen.

c. Choose one new data point at random as a new cen-
ter, using a weighted probability distribution where
a point x is chosen with probability proportional to
D(x)2.

d. Repeat Steps 2 and 3 until k centers have been cho-

(11.26)

sen.

e. Now that the initial centers have been chosen, pro-

ceed using standard k-means clustering.

2. TODO

(11.27)

11.4.5 EM for mixture of experts

The hidden variable is gjk, which’s meanining is:

{

gjk =

if ∥x j (cid:0) (cid:22)k∥2 is minimal for (cid:22)k

1;
0; otherwise

11.4.6 EM for DGMs with hidden variables

11.4.7 EM for the Student distribution *

11.4.4.3 Optimization

E-Step:

{

g(i+1)
jk =

M-Step:

if ∥x j (cid:0) (cid:22)(i)
k

1;
0; otherwise

∥2 is minimal for (cid:22)(i)
k

(cid:22)(i+1)
k

=

(cid:229)N

g(i+1)
jk x j

j=1
(cid:229) g(i+1)
jk

(11.28)

(11.29)

11.4.4.4 Tricks

Choosing k
TODO
Choosing the initial centroids(seeds)

11.4.8 EM for probit regression *

11.4.9 Derivation of the Q function

Theorem 11.1. (Jensen’s inequality) Let f be a convex
function(see Section A.1) deﬁned on a convex set S . If
li = 1,
x1; x2; (cid:1) (cid:1) (cid:1) ; xn 2 S and l1; l2; (cid:1) (cid:1) (cid:1) ; ln (cid:21) 0 with

n
(cid:229)
i=1

(

)

f

n
(cid:229)
i=1

lixi

(cid:20)

n
(cid:229)
i=1

li f (xi)

(11.30)

Proposition 11.1.

(

)

log

n
(cid:229)
i=1

lixi

(cid:21)

n
(cid:229)
i=1

li log(xi)

(11.31)

21 http://en.wikipedia.org/wiki/K-means++

Now let’s proof why the Q function should look like

11.4.10 Convergence of the EM Algorithm *

65

Equation 11.13:

ℓ((cid:18)) = log P(Dj(cid:18))
= log(cid:229)

P(D; zj(cid:18))

z

ℓ((cid:18)) (cid:0) ℓ((cid:18)t(cid:0)1) = log

P(Djz; (cid:18))P(zj(cid:18))

]
P(Djz; (cid:18))P(zj(cid:18))

11.4.10.1 Expected complete data log likelihood is a

lower bound

Note that ℓ((cid:18)) (cid:21) B((cid:18); (cid:18)t(cid:0)1), and ℓ((cid:18)t(cid:0)1) (cid:21) B((cid:18)t(cid:0)1; (cid:18)t(cid:0)1),
which means B((cid:18); (cid:18)t(cid:0)1) is an lower bound of ℓ((cid:18)). If we
maximize B((cid:18); (cid:18)t(cid:0)1), then ℓ((cid:18)) gets maximized, see Fig-
ure 11.4.

(cid:0) log P(Dj(cid:18)t(cid:0)1)

= log(cid:229)
z
[
(cid:229)
[
(cid:229)

= log

z

z

[
(cid:229)

(cid:0) log P(Dj(cid:18)t(cid:0)1)

= log

P(zjD; qt(cid:0)1)

z

(cid:0) log P(Dj(cid:18)t(cid:0)1)

(cid:21) (cid:229)

P(zjD; qt(cid:0)1) log

z
(cid:0) log P(Dj(cid:18)t(cid:0)1)
{
P(zjD; qt(cid:0)1)
[

z

= (cid:229)

P(Djz; (cid:18))P(zj(cid:18))

P(zjD; qt(cid:0)1)
P(zjD; qt(cid:0)1)

P(Djz; (cid:18))P(zj(cid:18))
P(zjD; qt(cid:0)1)

[

P(Djz; (cid:18))P(zj(cid:18))
P(zjD; qt(cid:0)1)

log

P(Djz; (cid:18))P(zj(cid:18))
P(zjD; qt(cid:0)1)P(Dj(cid:18)t(cid:0)1)

]}

]

]

]

]

B((cid:18); (cid:18)t(cid:0)1) ≜ ℓ((cid:18)t(cid:0)1)+

P(zjD; qt(cid:0)1) log

(cid:229)

z

)

[

P(Djz; (cid:18))P(zj(cid:18))
P(zjD; qt(cid:0)1)P(Dj(cid:18)t(cid:0)1)

(cid:18)t = arg max

(cid:18)

= arg max

(cid:18)

B((cid:18); (cid:18)t(cid:0)1)
{
ℓ((cid:18)t(cid:0)1)+

[

P(zjD; qt(cid:0)1) log

(cid:229)

z

P(Djz; (cid:18))P(zj(cid:18))
P(zjD; qt(cid:0)1)P(Dj(cid:18)t(cid:0)1)

Now drop terms which are constant w.r.t. (cid:18)

{

]}

}

= arg max

(cid:18)

= arg max

(cid:18)

= arg max

(cid:18)

≜ arg max

(cid:18)

(cid:229)

P(zjD; qt(cid:0)1) log [P(Djz; (cid:18))P(zj(cid:18))]

z

{

}

(cid:229)

P(zjD; qt(cid:0)1) log [P(D; zj(cid:18))]

z

{

}
zjD;qt(cid:0)1 log [P(D; zj(cid:18))]
E

Q((cid:18); (cid:18)t(cid:0)1)

(11.32)

(11.33)

Fig. 11.4: Graphical interpretation of a single iteration of
the EM algorithm: The function B((cid:18); (cid:18)t(cid:0)1) is bounded
above by the log likelihood function ℓ((cid:18)). The functions
are equal at (cid:18) = (cid:18)t(cid:0)1. The EM algorithm chooses (cid:18)t(cid:0)1 as
the value of (cid:18) for which B((cid:18); (cid:18)t(cid:0)1) is a maximum. Since
ℓ((cid:18)) (cid:21) B((cid:18); (cid:18)t(cid:0)1) increasing B((cid:18); (cid:18)t(cid:0)1) ensures that the
value of the log likelihood function ℓ((cid:18)) is increased at
each step.

Since the expected complete data log likelihood Q is
derived from B((cid:18); (cid:18)t(cid:0)1) by dropping terms which are con-
stant w.r.t. (cid:18), so it is also a lower bound to a lower bound
of ℓ((cid:18)).

11.4.10.2 EM monotonically increases the observed

data log likelihood

11.4.11 Generalization of EM Algorithm *

EM algorithm can be interpreted as F function’s
maximization-maximization algorithm, based on this in-
terpretation there are many variations and generalization,
e.g., generalized EM Algorithm(GEM).

66

11.4.11.1 F function’s maximization-maximization

algorithm

Deﬁnition 11.1. Given the probability distribution of the
hidden variable Z is ˜P(Z), deﬁne F function as the fol-
lowing:

F( ˜P; (cid:18)) = E ˜P [log P(X; Zjq)] + H( ˜P)

(11.34)

Where H( ˜P) = (cid:0)E ˜P log ˜P(Z), which is ˜P(Z)’s entropy.
Usually we assume that P(X; Zjq) is continuous w.r.t. (cid:18),
therefore F( ˜P; (cid:18)) is continuous w.r.t. ˜P and (cid:18).

Lemma 11.1. For a ﬁxed (cid:18), there is only one distribution
˜Pq which maximizes F( ˜P; (cid:18))

Assume (cid:18)t(cid:0)1 is the estimation of (cid:18) in the (t (cid:0) 1)-th iter-
ation, ˜Pt(cid:0)1 is the estimation of ˜P in the (t (cid:0)1)-th iteration.
Then in the t-th iteration two steps are:
1. for ﬁxed (cid:18)t(cid:0)1, ﬁnd ˜Pt that maximizes F( ˜P; (cid:18)t(cid:0)1);
2. for ﬁxed ˜Pt , ﬁnd (cid:18)t that maximizes F( ˜Pt ; (cid:18)).

Proof. (1) According to Lemma 11.1, we can get

˜Pt (Z) = P(ZjX; (cid:18)t(cid:0)1)

(2) According above, we can get

F( ˜Pt ; (cid:18)) = E ˜Pt [log P(X; Zjq)] + H( ˜Pt )

P(ZjX; (cid:18)t(cid:0)1) log P(X; Zjq) + H( ˜Pt )

= (cid:229)
Z

˜Pq(Z) = P(ZjX; (cid:18))

(11.35)

= Q((cid:18); (cid:18)t(cid:0)1) + H( ˜Pt )

and ˜Pq is continuous w.r.t. (cid:18).

Then

Proof. Given a ﬁxed (cid:18), we can get ˜Pq which maximizes
F( ˜P; (cid:18)). we construct the Lagrangian

(cid:18)t = arg max
q

F( ˜Pt ; (cid:18)) = arg max
q

Q((cid:18); (cid:18)t(cid:0)1)

L( ˜P; (cid:18)) = E ˜P [log P(X; Zjq)] (cid:0) E ˜P log ˜Pq(Z)

]

˜P(Z)

(11.36)

[
1 (cid:0)(cid:229)
Z

+ l

Take partial derivative with respect to ˜Pq(Z) then we

get

¶L
¶ ˜Pq(Z)

= log P(X; Zjq) (cid:0) log ˜Pq(Z) (cid:0) 1 (cid:0) l

Let it equal to 0, we can get

l = log P(X; Zjq) (cid:0) log ˜Pq(Z) (cid:0) 1

Then we can derive that

P(X; Zjq)

˜Pq(Z) is proportional to

P(X; Zjq)
˜Pq(Z)

= e1+l

) ˜Pq(Z) =

(cid:229)
Z

˜Pq(Z) = 1 ) (cid:229)
Z
P(X; Zj(cid:18))

˜Pq(Z) =

P(X; Zj(cid:18))
e1+l
P(X; Zj(cid:18))
e1+l = 1 ) P(Xj(cid:18)) = e1+l
P(X; Zj(cid:18))
= P(ZjX; (cid:18))
P(Xj(cid:18))

e1+l =

Lemma 11.2. If ˜Pq(Z) = P(ZjX; (cid:18)), then

F( ˜P; (cid:18)) = log P(Xj(cid:18))

(11.37)

Theorem 11.2. One iteration of EM algorithm can be im-
plemented as F function’s maximization-maximization.

11.4.11.2 The Generalized EM Algorithm(GEM)

In the formulation of the EM algorithm described above,
(cid:18)t was chosen as the value of (cid:18) for which Q((cid:18); (cid:18)t(cid:0)1)
was maximized. While this ensures the greatest increase
in ℓ((cid:18)), it is however possible to relax the requirement of
maximization to one of simply increasing Q((cid:18); (cid:18)t(cid:0)1) so
that Q((cid:18)t ; (cid:18)t(cid:0)1) (cid:21) Q((cid:18)t(cid:0)1; (cid:18)t(cid:0)1). This approach, to sim-
ply increase and not necessarily maximize Q((cid:18)t; (cid:18)t(cid:0)1)
is known as the Generalized Expectation Maximization
(GEM) algorithm and is often useful in cases where the
maximization is difﬁcult. The convergence of the GEM
algorithm is similar to the EM algorithm.

11.4.12 Online EM

11.4.13 Other EM variants *

11.5 Model selection for latent variable

models

When using LVMs, we must specify the number of latent
variables, which controls the model complexity. In partic-
ular, in the case of mixture models, we must specify K,
the number of clusters. Choosing these parameters is an
example of model selection. We discuss some approaches
below.

11.5.1 Model selection for probabilistic

models

E(D; K) ≜ 1
jDj

N
(cid:229)
i=1

∥xi (cid:0) ˆxi∥2

67

(11.38)

In the case of K-means, the reconstruction is given by
∥2, as explained in

ˆxi = (cid:22)zi , where zi = arg mink∥xi (cid:0) ˆ(cid:22)k
Section 11.4.2.6 TODO.

In supervised learning, we can always use cross valida-
tion to select between non-probabilistic models of differ-
ent complexity, but this is not the case with unsupervised
learning. The most common approach is to plot the recon-
struction error on the training set versus K, and to try to
identify a knee or kink in the curve.

11.6 Fitting models with missing data

Suppose we want to ﬁt a joint density model by maxi-
mum likelihood, but we have holes in our data matrix,
due to missing data (usually represented by NaNs). More
formally, let Oi j = 1 if component j of data case i is ob-
served, and let Oi j = 0 otherwise. Let X v = fxi j : Oi j =
1g be the visible data, and Xh = fxi j : Oi j = 0g be the
missing or hidden data. Our goal is to compute

ˆ(cid:18) = arg max

(cid:18)

p(X vj(cid:18); O)

(11.39)

Under the missing at random assumption (see Section

8.6.2), we have
TODO

11.6.1 EM for the MLE of an MVN with

missing data

TODO

The optimal Bayesian approach, discussed in Section 5.3,
is to pick the model with the largest marginal likelihood,
K(cid:3) = arg maxk p(Djk).

There are two problems with this. First, evaluating the
marginal likelihood for LVMs is quite difﬁcult. In prac-
tice, simple approximations, such as BIC, can be used (see
e.g., (Fraley and Raftery 2002)). Alternatively, we can use
the cross-validated likelihood as a performance measure,
although this can be slow, since it requires ﬁtting each
model F times, where Fis the number of CV folds.

The second issue is the need to search over a poten-
tially large number of models. The usual approach is to
perform exhaustive search over all candidate values ofK.
However, sometimes we can set the model to its maximal
size, and then rely on the power of the Bayesian Occams
razor to kill off unwanted components. An example of this
will be shown in Section TODO 21.6.1.6, when we dis-
cuss variational Bayes.

An alternative approach is to perform stochastic sam-
pling in the space of models. Traditional approaches, such
as (Green 1998, 2003; Lunn et al. 2009), are based on
reversible jump MCMC, and use birth moves to propose
new centers, and death moves to kill off old centers. How-
ever, this can be slow and difﬁcult to implement. A sim-
pler approach is to use a Dirichlet process mixture model,
which can be ﬁt using Gibbs sampling, but still allows for
an unbounded number of mixture components; see Sec-
tion TODO 25.2 for details.

Perhaps surprisingly, these sampling-based methods
can be faster than the simple approach of evaluating the
quality of eachKseparately. The reason is that ﬁtting the
model for each K is often slow. By contrast, the sampling
methods can often quickly determine that a certain value
of K is poor, and thus they need not waste time in that part
of the posterior.

11.5.2 Model selection for non-probabilistic

methods

What if we are not using a probabilistic model? For ex-
ample, how do we choose K for the K-means algorithm?
Since this does not correspond to a probability model,
there is no likelihood, so none of the methods described
above can be used.

An obvious proxy for the likelihood is the reconstruc-
tion error. Deﬁne the squared reconstruction error of a
data set D, using model complexity K, as follows:

Chapter 12
Latent linear models

12.1 Factor analysis

One problem with mixture models is that they only use a
single latent variable to generate the observations. In par-
ticular, each observation can only come from one of K
prototypes. One can think of a mixture model as using
K hidden binary variables, representing a one-hot encod-
ing of the cluster identity. But because these variables are
mutually exclusive, the model is still limited in its repre-
sentational power.

An alternative is to use a vector of real-valued latent
variables,zi 2 RL. The simplest prior to use is a Gaussian
(we will consider other choices later):

p(zi) = N (zij(cid:22)0; (cid:6)0)

(12.1)

If the observations are also continuous, so xi 2 RD, we
may use a Gaussian for the likelihood. Just as in linear
regression, we will assume the mean is a linear function
of the (hidden) inputs, thus yielding

p(xijzi; (cid:18)) = N (xijW zi + (cid:22); (cid:9) )

(12.2)

where W is a D (cid:2) L matrix, known as the factor loading
matrix, and (cid:9) is a D (cid:2) D covariance matrix. We take (cid:9)
to be diagonal, since the whole point of the model is to
force zi to explain the correlation, rather than baking it
in to the observations covariance. This overall model is
called factor analysis or FA. The special case in which
(cid:9) = s2I is called probabilistic principal components
analysis or PPCA. The reason for this name will become
apparent later.

12.1.1 FA is a low rank parameterization of

an MVN

FA can be thought of as a way of specifying a joint density
model on x using a small number of parameters. To see
this, note that from Equation 4.39, the induced marginal
distribution p(xij(cid:18)) is a Gaussian:

∫

p(xij(cid:18)) =

N (xijW zi + (cid:22); (cid:9) )N (zij(cid:22)0; (cid:6)0)dzi

= N (xijW (cid:22)0 + (cid:22); (cid:9) + W (cid:6)0W )

(12.3)

From this, we see that we can set (cid:22)0 = 0 without loss
of generality, since we can always absorb W (cid:22)0 into (cid:22).
Similarly, we can set (cid:6)0 = I without loss of generality,
because we can always emulate a correlated prior by using

deﬁning a new weight matrix,
rewrite Equation 12.6 and 12.2 as:

˜W = W (cid:6)

(cid:0) 1
2
0

. So we can

p(zi) = N (zij0; I)

p(xijzi; (cid:18)) = N (xijW zi + (cid:22); (cid:9) )

(12.4)

(12.5)

We thus see that FA approximates the covariance ma-
trix of the visible vector using a low-rank decomposition:

C ≜ cov[x] = W W T + (cid:9)

(12.6)

This only uses O(LD) parameters, which allows a ﬂexi-
ble compromise between a full covariance Gaussian, with
O(D2) parameters, and a diagonal covariance, with O(D)
parameters. Note that if we did not restrict (cid:9) to be diag-
onal, we could trivially set (cid:9) to a full covariance matrix;
then we could set W = 0, in which case the latent factors
would not be required.

12.1.2 Inference of the latent factors

p(zijxi; (cid:18)) = N (zij(cid:22)i; (cid:6)i)
(cid:6)i ≜ ((cid:6)(cid:0)1

0 + W T (cid:9) (cid:0)1W )(cid:0)1

= (I + W T (cid:9) (cid:0)1W )(cid:0)1

(cid:22)i ≜ (cid:6)i[W T (cid:9) (cid:0)1(xi (cid:0) (cid:22)) + (cid:6)(cid:0)1

0 (cid:22)0]

= (cid:6)iW T (cid:9) (cid:0)1(xi (cid:0) (cid:22))

(12.7)

(12.8)

(12.9)

(12.10)

(12.11)

Note that in the FA model, (cid:6)i is actually independent of
i, so we can denote it by (cid:6). Computing this matrix takes
O(L3 + L2D) time, and computing each (cid:22)i = E[zijxi; (cid:18)]
takes O(L2 + LD) time. The (cid:22)i are sometimes called the
latent scores, or latent factors.

69

70

12.1.3 Unidentiﬁability

Just like with mixture models, FA is also unidentiﬁable.
To see this, suppose R is an arbitrary orthogonal rotation
matrix, satisfying RRT = I. Let us deﬁne ˜W = W R,
then the likelihood function of this modiﬁed matrix is the
same as for the unmodiﬁed matrix, since W RRT W T +
(cid:9) = W W T + (cid:9) . Geometrically, multiplying W by an
orthogonal matrix is like rotating z before generating x.
To ensure a unique solution, we need to remove L(L (cid:0)
1)=2 degrees of freedom, since that is the number of or-
thonormal matrices of size L (cid:2) L.22 In total, the FA model
has D + LD (cid:0) L(L (cid:0) 1)=2 free parameters (excluding the
mean), where the ﬁrst term arises from (cid:9) . Obviously we
require this to be less than or equal to D(D + 1)=2, which
is the number of parameters in an unconstrained (but sym-
metric) covariance matrix. This gives us an upper bound
on L, as follows:

Lmax = ⌊D + 0:5(1 (cid:0)

p

1 + 8D)⌋

(12.12)

For example, D = 6 implies L (cid:20) 3. But we usually
never choose this upper bound, since it would result in
overﬁtting (see discussion in Section 12.3 on how to
choose L).

Unfortunately, even if we set L < Lmax, we still cannot
uniquely identify the parameters, since the rotational am-
biguity still exists. Non-identiﬁability does not affect the
predictive performance of the model. However, it does af-
fect the loading matrix, and hence the interpretation of
the latent factors. Since factor analysis is often used to
uncover structure in the data, this problem needs to be ad-
dressed. Here are some commonly used solutions:

• Forcing W to be orthonormal Perhaps the cleanest
solution to the identiﬁability problem is to force W to
be orthonormal, and to order the columns by decreas-
ing variance of the corresponding latent factors. This
is the approach adopted by PCA, which we will dis-
cuss in Section 12.2. The result is not necessarily more
interpretable, but at least it is unique.

• Forcing W to be lower triangular One way
to achieve identiﬁability, which is popular in the
Bayesian community (e.g., (Lopes and West 2004)), is
to ensure that the ﬁrst visible feature is only generated
by the ﬁrst latent factor, the second visible feature is
only generated by the ﬁrst two latent factors, and so
on. For example, if L = 3 and D = 4, the correspond
factor loading matrix is given by

22 To see this, note that there are L (cid:0) 1 free parameters in R in the
ﬁrst column (since the column vector must be normalized to unit
length), there are L (cid:0) 2 free parameters in the second column (which
must be orthogonal to the ﬁrst), and so on.

0

B
B
@

w11 0
0
w21 w22 0
w31 w32 w33
w41 w32 w43

1

C
C
A

W =

We also require that w j j > 0 for j = 1 : L. The to-
tal number of parameters in this constrained matrix is
D + DL (cid:0) L(L (cid:0) 1)=2, which is equal to the number of
uniquely identiﬁable parameters. The disadvantage of
this method is that the ﬁrst L visible variables, known
as the founder variables, affect the interpretation of
the latent factors, and so must be chosen carefully.
• Sparsity promoting priors on the weights Instead of
pre-specifying which entries in W are zero, we can
encourage the entries to be zero, using ℓ1 regulariza-
tion (Zou et al. 2006), ARD (Bishop 1999; Archam-
beau and Bach 2008), or spike-and-slab priors (Rattray
et al. 2009). This is called sparse factor analysis. This
does not necessarily ensure a unique MAP estimate,
but it does encourage interpretable solutions. See Sec-
tion 13.8 TODO.

• Choosing an informative rotation matrix There are
a variety of heuristic methods that try to ﬁnd rotation
matrices R which can be used to modify W (and hence
the latent factors) so as to try to increase the inter-
pretability, typically by encouraging them to be (ap-
proximately) sparse. One popular method is known as
varimax(Kaiser 1958).

• Use of non-Gaussian priors for the latent factors In
Section 12.6, we will dicuss how replacing p(zi) with a
non-Gaussian distribution can enable us to sometimes
uniquely identify W as well as the latent factors. This
technique is known as ICA.

12.1.4 Mixtures of factor analysers

The FA model assumes that the data lives on a low di-
mensional linear manifold. In reality, most data is better
modeled by some form of low dimensional curved mani-
fold. We can approximate a curved manifold by a piece-
wise linear manifold. This suggests the following model:
let the k’th linear subspace of dimensionality Lk be rep-
resented by W k, for k = 1 : K. Suppose we have a latent
indicator qi 2 f1; (cid:1) (cid:1) (cid:1) ; Kg specifying which subspace we
should use to generate the data. We then sample zi from a
Gaussian prior and pass it through the W k matrix (where
k = qi), and add noise. More precisely, the model is as
follows:

p(qij(cid:18)) = Cat(qi(cid:25))
p(zij(cid:18)) = N (zij0; I)
p(xijqi = k; zi; (cid:18)) = N (xijW zi + (cid:22)k; (cid:9) )

(12.13)

(12.14)
(12.15)

This is called a mixture of factor analysers(MFA) (Hin-
ton et al. 1997).

Another way to think about this model is as a low-rank
version of a mixture of Gaussians. In particular, this model
needs O(KLD) parameters instead of the O(KD2) param-
eters needed for a mixture of full covariance Gaussians.
This can reduce overﬁtting. In fact, MFA is a good generic
density model for high-dimensional real-valued data.

12.1.5 EM for factor analysis models

Below we state the results without proof. The derivation
can be found in (Ghahramani and Hinton 1996a). To ob-
tain the results for a single factor analyser, just set ric = 1
and c = 1 in the equations below. In Section 12.2.4 we will
see a further simpliﬁcation of these equations that arises
when ﬁtting a PPCA model, where the results will turn out
to have a particularly simple and elegant interpretation.

In the E-step, we compute the posterior responsibility

of cluster k for data point i using

rik ≜ p(qi = kjxi; (cid:18)) (cid:181) pkN (xij(cid:22)k; W kW T

k (cid:9) k) (12.16)

The conditional posterior for zi is given by

p(zijxi; qi = k; (cid:18)) = N (zij(cid:22)ik; (cid:6)ik)
k (cid:9) (cid:0)1
k (cid:9) (cid:0)1

(cid:6)ik ≜ (I + W T
(cid:22)ik ≜ (cid:6)ikW T

k W )(cid:0)1
k (xi (cid:0) (cid:22)k)

k

(12.17)

(12.18)

(12.19)

Note that these updates are for vanilla EM. A much
faster version of this algorithm, based on ECM, is de-
scribed in (Zhao and Yu 2008).

71

12.1.6 Fitting FA models with missing data

In many applications, such as collaborative ﬁltering, we
have missing data. One virtue of the EM approach to ﬁt-
ting an FA/PPCA model is that it is easy to extend to this
case. However, overﬁtting can be a problem if there is a
lot of missing data. Consequently it is important to per-
form MAP estimation or to use Bayesian inference. See
e.g., (Ilin and Raiko 2010) for details.

12.2 Principal components analysis (PCA)

Consider the FA model where we constrain (cid:9) = s2I,
and W to be orthonormal. It can be shown (Tipping
and Bishop 1999) that, as s2 ! 0, this model reduces to
classical (nonprobabilistic) principal components anal-
ysis(PCA), also known as the Karhunen Loeve trans-
form. The version where s2 > 0 is known as probabilis-
tic PCA(PPCA) (Tipping and Bishop 1999), orsensible
PCA(Roweis 1997).

In the M step, it is easiest to estimate (cid:22)k and W k at the
same time, by deﬁning ˜W k = (W k; (cid:22)k), ˜z = (z; 1), also,
deﬁne

12.2.1 Classical PCA

12.2.1.1 Statement of the theorem

˜W k = (W k; (cid:22)k)
˜z = (z; 1)
bik ≜ E[ ˜zjxi; qi = k] = E[((cid:22)ik; 1)]
Cik ≜ E[ ˜z ˜zT jxi; qi = k]

(

=

E[zzT jxi; qi = k] E[zjxi; qi = k]
E[zjxi; qi = k]T

1

Then the M step is as follows:

ˆpk =

N
(cid:229)
i=1

1
N
(

rik

) (

ˆ˜W k =

N
(cid:229)
i=1

rikxibT
ik
[

N
(cid:229)
i=1

rikxiCT
ik

)(cid:0)1

]

)

(12.20)

(12.21)

(12.22)

(12.23)

(12.24)

(12.25)

(12.26)

ˆ(cid:9) =

1
N

diag

N
(cid:229)
i=1

rik(xi (cid:0) ˆ˜W ikbik)xT

i

(12.27)

The synthesis viewof classical PCA is summarized in the
forllowing theorem.

Theorem 12.1. Suppose we want to ﬁnd an orthogonal set
of L linear basis vectors w j 2 RD, and the corresponding
scores zi 2 RL, such that we minimize the average recon-
struction error

J(W ; Z) =

1
N

N
(cid:229)
i=1

∥xi (cid:0) ˆxi∥2

(12.28)

where ˆxi = W zi, subject to the constraint that W is or-
thonormal. Equivalently, we can write this objective as
follows

J(W ; Z) =

1
N

∥X (cid:0) W ZT ∥2

(12.29)

where Z is an N (cid:2) L matrix with the zi in its rows, and
∥A∥F is the Frobenius norm of matrix A, deﬁned by

72

v
u
u
t

M
(cid:229)
i=1

N
(cid:229)
j=1

∥A∥F ≜

√

a2
i j =

tr(AT A)

(12.30)

standard practice to standardize the data ﬁrst, or equiv-
alently, to work with correlation matrices instead of co-
variance matrices.

the
of
i=1 xixT
i .

The optimal solution is obtained by setting ˆW = V L,
where V L contains the L eigenvectors with largest
eigenvalues
covariance matrix,
empirical
ˆ(cid:6) = 1
(cid:229)N
(We assume the xi have zero
N
mean, for notational simplicity.) Furthermore, the op-
timal low-dimensional encoding of the data is given by
ˆzi = W T xi, which is an orthogonal projection of the
data onto the column space spanned by the eigenvectors.

An example of this is shown in Figure 12.1(a) for D = 2
and L = 1. The diagonal line is the vector w1; this is called
the ﬁrst principal component or principal direction. The
data points xi 2 R2 are orthogonally projected onto this
line to get zi 2 R. This is the best 1-dimensional approxi-
mation to the data. (We will discuss Figure 12.1(b) later.)

12.2.1.2 Proof *

See Section 12.2.2 of MLAPP.

12.2.2 Singular value decomposition (SVD)

We have deﬁned the solution to PCA in terms of eigenvec-
tors of the covariance matrix. However, there is another
way to obtain the solution, based on the singular value
decomposition, or SVD. This basically generalizes the
notion of eigenvectors from square matrices to any kind
of matrix.

Theorem 12.2. (SVD). Any matrix can be decomposed as
follows

V T
|{z}
D(cid:2)D

(12.31)

(cid:6)|{z}
N(cid:2)D

X|{z}
N(cid:2)D

= U|{z}
N(cid:2)N
where U is an N (cid:2) N matrix whose columns are or-
thornormal(so U T U = I), V is D (cid:2) D matrix whose rows
and columns are orthonormal (so V T V = V V T = I D),
and (cid:6) is a N (cid:2) D matrix containing the r = min(N; D)
singular values si (cid:21) 0 on the main diagonal, with 0s ﬁll-
ing the rest of the matrix.

This shows how to decompose the matrix X into the
product of three matrices: V describes an orthonormal ba-
sis in the domain, and U describes an orthonormal basis
in the co-domain, and (cid:6) describes how much the vectors
in V are stretched to give the vectors in U .

Since there are at most D singular values (assuming
N > D), the last ND columns of U are irrelevant, since
they will be multiplied by 0. The economy sized SVD, or
thin SVD, avoids computing these unnecessary elements.
Let us denote this decomposition by ˆU ˆ(cid:6) ˆV
.If N > D,
we have

T

X|{z}
N(cid:2)D

= ˆU|{z}
N(cid:2)D

ˆ(cid:6)|{z}
D(cid:2)D

T
ˆV
|{z}
D(cid:2)D

as in Figure 12.2(a). If N < D, we have

X|{z}
N(cid:2)D

= ˆU|{z}
N(cid:2)N

ˆ(cid:6)|{z}
N(cid:2)N

T
ˆV
|{z}
N(cid:2)D

(12.32)

(12.33)

the

takes
Computing
O(ND min(N; D)) time (Golub and van Loan 1996,
p254).

economy-sized

SVD

The connection between eigenvectors and singular vec-

tors is the following:

(a)

(b)

Fig. 12.1: An illustration of PCA and PPCA where D = 2
and L = 1. Circles are the original data points, crosses are
the reconstructions. The red star is the data mean. (a)
PCA. The points are orthogonally projected onto the line.
(b) PPCA. The projection is no longer orthogonal: the
reconstructions are shrunk towards the data mean (red
star).

The principal directions are the ones along which the
data shows maximal variance. This means that PCA can
be misled by directions in which the variance is high
merely because of the measurement scale. It is therefore

∥X (cid:0) X L∥F (cid:25) sL

73

(12.38)

Furthermore, one can show that the SVD offers the best
rank L approximation to a matrix (best in the sense of
minimizing the above Frobenius norm).

Let us connect this back to PCA. Let X = U (cid:6)V T be
ˆW = V , and that

a truncated SVD of X. We know that
ˆZ = X ˆW , so

ˆZ = U (cid:6)V T V = U (cid:6)

(12.39)

Furthermore, the optimal reconstruction is given by ˆX =
Z ˆW ,so we ﬁnd

ˆX = U (cid:6)V T

(12.40)

This is precisely the same as a truncated SVD approxima-
tion! This is another illustration of the fact that PCA is the
best low rank approximation to the data.

12.2.3 Probabilistic PCA

Theorem 12.3. ((Tipping and Bishop 1999)). Consider a
factor analysis model in which (cid:9) = s2I and W is or-
thogonal. The observed data log likelihood is given by

log p(XjW ; s2I) = (cid:0) N
2
= (cid:0) N
2

ln jCj (cid:0) 1
2

N
(cid:229)
i=1

i C(cid:0)1xi
xT

ln jCj + tr(C(cid:0)1(cid:6))

(12.41)

where C = W W T + s2I and (cid:6) = 1
i =
N
1
N XX T . (We are assuming centred data, for notational
simplicity.) The maxima of the log-likelihood are given by

i=1 xixT

(cid:229)N

ˆW = V ((cid:3) (cid:0) s2I)

1
2 R

(12.42)

where R is an arbitrary L (cid:2) L orthogonal matrix, V is
the D (cid:2) L matrix whose columns are the ﬁrst L eigenvec-
tors of (cid:6), and (cid:3) is the corresponding diagonal matrix of
eigenvalues. Without loss of generality, we can set R = I.
Furthermore, the MLE of the noise variance is given by

ˆs2 =

1
D (cid:0) L

D
(cid:229)
j=L+1

lj

(12.43)

which is the average variance associated with the dis-
carded dimensions.

Thus, as s2 ! 0, we have ˆW ! V , as in classical
PCA. What about ˆZ? It is easy to see that the posterior
over the latent factors is given by

(a)

(b)

Fig. 12.2: (a) SVD decomposition of non-square matrices
X = U (cid:6)V T . The shaded parts of (cid:6), and all the
off-diagonal terms, are zero. The shaded entries in U and
(cid:6) are not computed in the economy-sized version, since
they are not needed. (b) Truncated SVD approximation
of rank L.

U = evec(XX T )
V = evec(X T X)
(cid:6)2 = eval(XX T ) = eval(X T X)

(12.34)

(12.35)

(12.36)

For the proof please read Section 12.2.3 of MLAPP.

Since the eigenvectors are unaffected by linear scaling
of a matrix, we see that the right singular vectors of X are
equal to the eigenvectors of the empirical covariance ˆ(cid:6).
Furthermore, the eigenvalues of ˆ(cid:6) are a scaled version of
the squared singular values.

However, the connection between PCA and SVD goes
deeper. From Equation 12.31, we can represent a rank r
matrix as follows:
0

0

1

1

X = s1

@

(

A

)

(cid:0) v1 (cid:0)

+ (cid:1) (cid:1) (cid:1) + sr

@

(

A

)

(cid:0) vT
r

(cid:0)

j
u1
j

j
ur
j

If the singular values die off quickly, we can produce a
rank L approximation to the matrix as follows:
1

0

1

0

X (cid:25) s1

(

@

A

j
u1
j
= U :;1:L(cid:6)1:L;1:LV T

(cid:0) v1 (cid:0)

:;1:L

)

+ (cid:1) (cid:1) (cid:1) + sr

@

j
uL
j

(

A

)

(cid:0) vT
L

(cid:0)

(12.37)

This is called a truncated SVD (see Figure 12.2(b)).

One can show that the error in this approximation is

given by

74

p(zijxi; ˆ(cid:18)) = N (zij ˆF

T

(cid:0)1 ˆW
T ˆW + s2I

xi; s2 ˆF

(cid:0)1

)

(12.44)

(12.45)

ˆF ≜ ˆW

(Do not confuse F = W T W + s2I with C = W W T +
s2I.) Hence, as s2 ! 0, we ﬁnd ˆW ! V , ˆF ! I and
zi ! V T xi. Thus the posterior mean is obtained by an
orthogonal projection of the data onto the column space
of V , as in classical PCA.

Note, however, that if s2 ! 0, the posterior mean is
not an orthogonal projection, since it is shrunk somewhat
towards the prior mean, as illustrated in Figure 12.1(b).
This sounds like an undesirable property, but it means that
the reconstructions will be closer to the overall data mean,
ˆ(cid:22) = ¯x.

12.2.4 EM algorithm for PCA

Although the usual way to ﬁt a PCA model uses eigen-
vector methods, or the SVD, we can also use EM, which
will turn out to have some advantages that we discuss be-
low. EM for PCA relies on the probabilistic formulation
of PCA. However the algorithm continues to work in the
zero noise limit, s2 = 0, as shown by (Roweis 1997).

Let ˜Z be a L (cid:2) N matrix storing the posterior means
representations) along its columns.
˜X = X T store the original data along its

(low-dimensional
Similarly, let
columns. From Equation 12.44, when s2 = 0, we have

points in R2 attached by springs to a rigid rod, whose ori-
entation is deﬁned by a vector w. Let zi be the location
where the i’th spring attaches to the rod. See Figure 12.11
of MLAPP for an illustration.

Apart from this pleasing intuitive interpretation, EM
for PCA has the following advantages over eigenvector
methods:
• EM can be faster. In particular, assuming N; D ≫ L,
the dominant cost of EM is the projection operation
in the E step, so the overall time is O(T LND), where
T is the number of iterations. This is much faster
than the O(min(ND2; DN2)) time required by straight-
forward eigenvector methods, although more sophisti-
cated eigenvector methods, such as the Lanczos algo-
rithm, have running times comparable to EM.

• EM can be implemented in an online fashion, i.e., we
can update our estimate of W as the data streams in.
• EM can handle missing data in a simple way (see Sec-

tion 12.1.6).

• EM can be extended to handle mixtures of PPCA/ FA

models.

• EM can be modiﬁed to variational EM or to variational

Bayes EM to ﬁt more complex models.

12.3 Choosing the number of latent

dimensions

˜Z = (W T W )(cid:0)1W T ˜X

(12.46)

This constitutes the E step. Notice that this is just an or-
thogonal projection of the data.

In Section 11.5, we discussed how to choose the number
of components K in a mixture model. In this section, we
discuss how to choose the number of latent dimensions L
in a FA/PCA model.

From Equation 12.26, the M step is given by
)(cid:0)1
) (

(

ˆW =

xiE[zi]T

E[zi]E[zi]T

(12.47)

N
(cid:229)
i=1

N
(cid:229)
i=1

where we exploited the fact that (cid:6) = cov[zijxi; (cid:18)] = 0
when s2 = 0.

(Tipping and Bishop 1999) showed that the only sta-
ble ﬁxed point of the EM algorithm is the globally op-
timal solution. That is, the EM algorithm converges to a
solution where W spans the same linear subspace as that
deﬁned by the ﬁrst L eigenvectors. However, if we want
W to be orthogonal, and to contain the eigenvectors in
descending order of eigenvalue, we have to orthogonalize
the resulting matrix (which can be done quite cheaply).
Alternatively, we can modify EM to give the principal ba-
sis directly (Ahn and Oh 2003).

This algorithm has a simple physical analogy in the
case D = 2 and L = 1(Roweis 1997). Consider some

12.3.1 Model selection for FA/PPCA

TODO

12.3.2 Model selection for PCA

TODO

12.4 PCA for categorical data

In this section, we consider extending the factor analy-
sis model to the case where the observed data is categori-
cal rather than real-valued. That is, the data has the form

yi j 2 f1; :::;Cg, where j = 1 : R is the number of observed
response variables. We assume each yi j is generated from
a latent variable zi 2 RL, with a Gaussian prior, which is
passed through the softmax function as follows:

p(zi) = N (zij0; I)
R
(cid:213)
j=1

p(yijzi; (cid:18)) =

Cat(yirjS(W T

r zi + w0r))

(12.48)

(12.49)

where W r 2 RL is the factor loading matrix for response
j, and W 0r 2 RM is the offset term for response r, and
(cid:18) = (W r; W 0r)R
r=1. (We need an explicit offset term,
since clamping one element of zi to 1 can cause problems
when computing the posterior covariance.) As in factor
analysis, we have deﬁned the prior mean to be (cid:22)0 = 0
and the prior covariance V 0 = I, since we can capture
non-zero mean by changing w0 j and non-identity covari-
ance by changing W r. We will call this categorical PCA.
See Chapter 27 TODO for a discussion of related models.
In (Khan et al. 2010), we show that this model out-
performs ﬁnite mixture models on the task of imputing
missing entries in design matrices consisting of real and
categorical data. This is useful for analysing social science
survey data, which often has missing data and variables of
mixed type.

12.5 PCA for paired and multi-view data

12.5.1 Supervised PCA (latent factor

regression)

12.5.2 Discriminative supervised PCA

12.5.3 Canonical correlation analysis

12.6 Independent Component Analysis

(ICA)

Let xt 2 RD be the observed signal at the sensors at time
t, and zt 2 RL be the vector of source signals. We assume
that

xt = W zt + ϵt
(12.50)
where W is an D (cid:2) L matrix, and ϵt (cid:24) N (0; (cid:9) ). In this
section, we treat each time point as an independent obser-
vation, i.e., we do not model temporal correlation (so we
could replace the t index with i, but we stick with t to be
consistent with much of the ICA literature). The goal is to
infer the source signals, p(zt jxt ; (cid:18)). In this context, W is
called the mixing matrix. If L = D (number of sources =

number of sensors), it will be a square matrix. Often we
will assume the noise level, j(cid:9) j, is zero, for simplicity.

75

So far, the model is identical to factor analysis. How-
ever, we will use a different prior for p(zt ). In PCA, we
assume each source is independent, and has a Gaussian
distribution. We will now relax this Gaussian assumption
and let the source distributions be any non-Gaussian dis-
tribution

p(zt ) =

p j(zt j)

(12.51)

L
(cid:213)
j=1

Without loss of generality, we can constrain the variance
of the source distributions to be 1, because any other vari-
ance can be modelled by scaling the rows of W appro-
priately. The resulting model is known as independent
component analysis or ICA.

The reason the Gaussian distribution is disallowed as a
source prior in ICA is that it does not permit unique recov-
ery of the sources. This is because the PCA likelihood is
invariant to any orthogonal transformation of the sources
zt and mixing matrix W . PCA can recover the best lin-
ear subspace in which the signals lie, but cannot uniquely
recover the signals themselves.

ICA requires that W is square and hence invertible.
In the non-square case (e.g., where we have more sources
than sensors), we cannot uniquely recover the true sig-
nal, but we can compute the posterior p(zt jxt ; ˆW ), which
represents our beliefs about the source. In both cases, we
need to estimate Was well as the source distributions p j.
We discuss how to do this below.

12.6.1 Maximum likelihood estimation

In this section, we discuss ways to estimate square mix-
ing matrices W for the noise-free ICA model. As usual,
we will assume that the observations have been centered;
hence we can also assume z is zero-mean. In addition, we
assume the observations have been whitened, which can
be done with PCA.

If the data is centered and whitened, we have E[xxT ] =

I. But in the noise free case, we also have

cov[x] = E[xxT ] = W E[zzT ]W T

(12.52)

Hence we see that W must be orthogonal. This reduces
the number of parameters we have to estimate from D2 to
D(D (cid:0) 1)=2. It will also simplify the math and the algo-
rithms.

Let V = W (cid:0)1; these are often called the recogni-
tion weights, as opposed to W , which are the generative
weights.

Since x = W z, we have, from Equation 2.46,

76

px(W zt ) = pz(zt )jdet(W (cid:0)1)j
= pz(V xt )jdet(V )j

(12.53)

Hence we can write the log-likelihood, assuming T iid
samples, as follows:

1
T

log p(DjV ) = log jdet(V )j +

1
T

L
(cid:229)
j=1

T
(cid:229)
t=1

log p j(vT

j xt )

where v j is the j’th row of V . Since we are constraining
V to be orthogonal, the ﬁrst term is a constant, so we can
drop it. We can also replace the average over the data with
an expectation operator to get the following objective

NLL(V ) =

L
(cid:229)
j=1

E[G j(z j)]

(12.54)

j x and G j(z) ≜ (cid:0) log p j(z). We want to
where z j = vT
minimize this subject to the constraint that the rows of V
are orthogonal. We also want them to be unit norm, since
this ensures that the variance of the factors is unity (since,
with whitened data, E[vT
j x] = ∥v j∥2, which is necessary
to ﬁx the scale of the weights. In otherwords, V should be
an orthonormal matrix.

It is straightforward to derive a gradient descent algo-
rithm to ﬁt this model; however, it is rather slow. One can
also derive a faster algorithm that follows the natural gra-
dient; see e.g., (MacKay 2003, ch 34) for details. A pop-
ular alternative is to use an approximate Newton method,
which we discuss in Section 12.6.2. Another approach is
to use EM, which we discuss in Section 12.6.3.

12.6.2 The FastICA algorithm

12.6.3 Using EM

12.6.4 Other estimation principles *

Chapter 13
Sparse linear models

77

Chapter 14
Kernels

14.1 Introduction

We give several examples below.

So far in this book, we have been assuming that each ob-
ject that we wish to classify or cluster or process in any-
way can be represented as a ﬁxed-size feature vector, typ-
ically of the form xi 2 RD. However, for certain kinds of
objects, it is not clear how to best represent them as ﬁxed-
sized feature vectors. For example, how do we represent a
text document or protein sequence, which can be of vari-
able length? or a molecular structure, which has complex
3d geometry? or an evolutionary tree, which has variable
size and shape?

One approach to such problems is to deﬁne a genera-
tive model for the data, and use the inferred latent repre-
sentation and/or the parameters of the model as features,
and then to plug these features in to standard methods. For
example, in Chapter 28 TODO, we discuss deep learning,
which is essentially an unsupervised way to learn good
feature representations.

Another approach is to assume that we have some way
of measuring the similarity between objects, that doesnt
require preprocessing them into feature vector format. For
example, when comparing strings, we can compute the
edit distance between them. Let k(x; x′) (cid:21) 0 be some
measure of similarity between objects k(x; x′) 2 X , we
will call k a kernel function. Note that the word kernel
has several meanings; we will discuss a different interpre-
tation in Section 14.7.1 TODO.

In this chapter, we will discuss several kinds of kernel
functions. We then describe some algorithms that can be
written purely in terms of kernel function computations.
Such methods can be used when we dont have access to
(or choose not to look at) the inside of the objects x that
we are processing.

14.2 Kernel functions

Deﬁnition 14.1. A kernel function23 is a real-valued
function of two arguments, k(x; x′) 2 R. Typically the
function is symmetric (i.e., k(x; x′) = k(x′; x), and
non-negative (i.e., k(x; x′) (cid:21) 0).

23

function

http://en.wikipedia.org/wiki/Kernel_

14.2.1 RBF kernels

The Gaussian kernel or squared exponential kernel(SE
kernel) is deﬁned by
(

)

k(x; x′) = exp

(x (cid:0) x′)T (cid:6)(cid:0)1(x (cid:0) x′)

(14.1)

(cid:0) 1
2

If (cid:6) is diagonal, this can be written as
(

)

k(x; x′) = exp

(cid:0) 1
2

D
(cid:229)
j=1

1
s2
j

(x j (cid:0) x′

j)2

(14.2)

We can interpret the sj as deﬁning the characteristic
length scale of dimension j.If sj = ¥, the corresponding
dimension is ignored; hence this is known as the ARD
kernel. If (cid:6) is spherical, we get the isotropic kernel

(

k(x; x′) = exp

(cid:0)

)

∥x (cid:0) x′∥2
2s2

(14.3)

Here s2 is known as the bandwidth. Equation 14.4
is an example of a radial basis function or RBF kernel,
since it is only a function of ∥x (cid:0) x′∥2.

14.2.2 TF-IDF kernels

k(x; x′) =

ϕ(x)T ϕ(x′)
∥ϕ(vecx)∥2∥ϕ(x′)∥2

(14.4)

where ϕ(x) = tf-idf(x).

14.2.3 Mercer (positive deﬁnite) kernels

If the kernel function satisﬁes the requirement that the
Gram matrix, deﬁned by

79

80

0

B
@

K ≜

k(x1; x2) (cid:1) (cid:1) (cid:1) k(x1; xN)

...

...

k(xN; x1) (cid:1) (cid:1) (cid:1) k(xN; xN)

1

C
A

...

(14.5)

14.2.4 Linear kernels

k(x; x′) = xT x′

(14.10)

be positive deﬁnite for any set of inputs fxigN
i=1. We call
such a kernel a Mercer kernel,or positive deﬁnite ker-
nel.

If the Gram matrix is positive deﬁnite, we can compute

an eigenvector decomposition of it as follows

K = U T (cid:3)U

(14.6)

where (cid:3) is a diagonal matrix of eigenvalues li > 0.

Now consider an element of K:

ki j = ((cid:3)

1

2 U :;i)T ((cid:3)

1
2 U :; j)

(14.7)

Let us deﬁne ϕ(xi) = (cid:3)

1
2 U :;i, then we can write

ki j = ϕ(xi)T ϕ(x j)

(14.8)

Thus we see that the entries in the kernel matrix can
be computed by performing an inner product of some fea-
ture vectors that are implicitly deﬁned by the eigenvectors
U . In general, if the kernel is Mercer, then there exists a
function ϕ mapping x 2 X to RD such that

k(x; x′) = ϕ(x)T ϕ(x′)

(14.9)

where ϕ depends on the eigen functions of k(so D is a
potentially inﬁnite dimensional space).

For example, consider the (non-stationary) polynomial
kernel k(x; x′) = (gxx′ + r)M, where r > 0. One can
show that the corresponding feature vector ϕ(x) will con-
tain all terms up to degree M. For example, if M = 2; g =
r = 1 and x; x′ 2 R2, we have

(xx′ + 1)2 = (1 + x1x′
= 1 + 2x1x′
= ϕ(x)T ϕ(x′)

1 + x2 + x′
1 + 2x2x′

2)2
2 + (x1x′

p

p

where ϕ(x) = (1;

2x1;

2x2; x2

1; x2
2;

p

2x1x2)

1)2 + (x2x′

2)2x1x′

1x2x′

2

In the case of a Gaussian kernel, the feature map lives
in an inﬁnite dimensional space. In such a case, it is
clearly infeasible to explicitly represent the feature vec-
tors.

In general, establishing that a kernel is a Mercer kernel
is difﬁcult, and requires techniques from functional anal-
ysis. However, one can show that it is possible to build up
new Mercer kernels from simpler ones using a set of stan-
dard rules. For example, if k1 and k2 are both Mercer, so is
k(x; x′) = k1(x; x′) + k2(x; x′) =. See e.g., (Schoelkopf
and Smola 2002) for details.

14.2.5 Matern kernels

The Matern kernel, which is commonly used in Gaussian
process regression (see Section 15.2), has the following
form

k(r) =

21(cid:0)n
G(n)

( p

2nr
ℓ

)n

p

2nr
ℓ

Kn

(14.11)

where r = ∥x (cid:0) x′∥, n > 0, ℓ > 0, and Kn is a modiﬁed
Bessel function. As n ! ¥, this approaches the SE kernel.
If n = 1

2 , the kernel simpliﬁes to

k(r) = exp((cid:0)r=ℓ)

(14.12)

If D = 1, and we use this kernel to deﬁne a Gaussian
process (see Chapter 15 TODO), we get the Ornstein-
Uhlenbeck process, which describes the velocity of a
particle undergoing Brownian motion (the corresponding
function is continuous but not differentiable, and hence is
very jagged).

14.2.6 String kernels

Now let ϕs(x) denote the number of times that substrings
appears in string x. We deﬁne the kernel between two
strings x and x′ as

k(x; x′) = (cid:229)
s2A(cid:3)

wsϕs(x)ϕs(x′)

(14.13)

where ws (cid:21) 0 and A(cid:3) is the set of all strings (of any
length) from the alphabet A(this is known as the Kleene
star operator). This is a Mercer kernel, and be computed
in O(jxj + jx′j) time (for certain settings of the weights
fwsg) using sufﬁx trees (Leslie et al. 2003; Vishwanathan
and Smola 2003; Shawe-Taylor and Cristianini 2004).

There are various cases of interest. If we set ws = 0for
jsj > 1 we get a bag-of-characters kernel. This deﬁnes
ϕ(x) to be the number of times each character in A oc-
curs in x.If we require s to be bordered by white-space,
we get a bag-of-words kernel, where ϕ(x) counts how
many times each possible word occurs. Note that this is
a very sparse vector, since most words will not be present.
If we only consider strings of a ﬁxed lengthk, we get the k-
spectrum kernel. This has been used to classify proteins
into SCOP superfamilies (Leslie et al. 2003).

14.2.7 Pyramid match kernels

14.2.8 Kernels derived from probabilistic

generative models

Suppose we have a probabilistic generative model of
feature vectors, p(xj(cid:18)). Then there are several ways we
can use this model to deﬁne kernel functions, and thereby
make the model suitable for discriminative tasks. We
sketch two approaches below.

14.2.8.1 Probability product kernels
∫

k(xi; x j) =

p(xjxi)rp(xjx j)rdx

(14.14)

where r > 0, and p(xjxi) is often approximated
by p(xj ˆ(cid:18)(xi)),where ˆ(cid:18)(xi) is a parameter estimate
computed using a single data vector. This is called a
probability product kernel(Jebara et al. 2004).

Although it seems strange to ﬁt a model to a single data
point, it is important to bear in mind that the ﬁtted model
is only being used to see how similar two objects are. In
particular, if we ﬁt the model to xi and then the model
thinks x j is likely, this means that xi and x j are similar.
For example, suppose p(xj(cid:18)) (cid:24) N ((cid:22); s2I), where s2 is
ﬁxed. If r = 1, and we use ˆ(cid:22)(xi) = xi and ˆ(cid:22)(x j) = x j,
we ﬁnd (Jebara et al. 2004, p825) that

k(xi; x j) =

1
(4ps2)D=2

exp

(

(cid:0) 1
4s2

)

∥xi (cid:0) x j∥2

(14.15)

which is (up to a constant factor) the RBF kernel.

It turns out that one can compute Equation 14.14 for
a variety of generative models, including ones with latent
variables, such as HMMs. This provides one way to de-
ﬁne kernels on variable length sequences. Furthermore,
this technique works even if the sequences are of real-
valued vectors, unlike the string kernel in Section 14.2.6.
See (Jebara et al. 2004) for further details

14.2.8.2 Fisher kernels

A more efﬁcient way to use generative models to deﬁne
kernels is to use a Fisher kernel (Jaakkola and Haussler
1998) which is deﬁned as follows:

k(xi; x j) = g(xi)T F (cid:0)1g(x j)

(14.16)

where g is the gradient of the log likelihood, or score vec-
tor, evaluated at the MLE ˆ(cid:18)

g(x) ≜ d
d(cid:18)

log p(xj(cid:18))j ˆ(cid:18)

81

(14.17)

and F is the Fisher information matrix, which is essen-
tially the Hessian:
[

F ≜

¶2
¶qi¶qj

]
log p(xj(cid:18))

j ˆ(cid:18)

(14.18)

Note that ˆ(cid:18) is a function of all the data, so the similarity
of xi and x j is computed in the context of all the data as
well. Also, note that we only have to ﬁt one model.

14.3 Using kernels inside GLMs

14.3.1 Kernel machines

We deﬁne a kernel machine to be a GLM where the input
feature vector has the form

ϕ(x) = (k(x; (cid:22)1); (cid:1) (cid:1) (cid:1) ; k(x; (cid:22)K))

(14.19)

where (cid:22)k 2 X are a set of K centroids. If k is an RBF
kernel, this is called an RBF network. We discuss ways
to choose the (cid:22)k parameters below. We will call Equation
14.19 a kernelised feature vector. Note that in this ap-
proach, the kernel need not be a Mercer kernel.

We can use the kernelized feature vector for logistic
regression by deﬁning p(yjx; (cid:18)) = Ber(yjwT ϕ(x)). This
provides a simple way to deﬁne a non-linear decision
boundary. For example, see Figure 14.1.

We

can also use

inside a linear

tor
p(yjx; (cid:18)) = N (yjwT ϕ(x); s2).

the kernelized feature vec-
regression model by deﬁning

14.3.2 L1VMs, RVMs, and other sparse

vector machines

The main issue with kernel machines is: how do we
choose the centroids (cid:22)k? We can use sparse vector
machine, L1VM, L2VM, RVM, SVM.

14.4 The kernel trick

Rather than deﬁning our feature vector in terms of kernels,
ϕ(x) = (k(x; x1); (cid:1) (cid:1) (cid:1) ; k(x; xN)), we can instead work
with the original feature vectors x, but modify the algo-
rithm so that it replaces all inner products of the form

82

(a)

(b)

(c)

Fig. 14.1: (a) xor truth table. (b) Fitting a linear logistic
regression classiﬁer using degree 10 polynomial
expansion. (c) Same model, but using an RBF kernel
with centroids speciﬁed by the 4 black crosses.

< xi; x j > with a call to the kernel function, k(xi; x j).
This is called the kernel trick. It turns out that many al-
gorithms can be kernelized in this way. We give some ex-
amples below. Note that we require that the kernel be a
Mercer kernel for this trick to work.

14.4.1 Kernelized KNN

The Euclidean distance can be unrolled as

∥xi (cid:0) x j∥ =< xi; xi > + < x j; x j > (cid:0)2 < xi; x j >

(14.20)
then by replacing all < xi; x j > with k(xi; x j) we get
Kernelized KNN.

14.4.2 Kernelized K-medoids clustering

K-medoids algorothm is similar to K-means(see Section
11.4.4), but instead of representing each clusters centroid
by the mean of all data vectors assigned to this cluster, we
make each centroid be one of the data vectors themselves.
Thus we always deal with integer indexes, rather than data
objects.

This algorithm can be kernelized by using Equation

14.20 to replace the distance computation.

14.4.3 Kernelized ridge regression

Applying the kernel trick to distance-based methods was
straightforward. It is not so obvious how to apply it to
parametric models such as ridge regression. However, it
can be done, as we now explain. This will serve as a good
warm up for studying SVMs.

14.4.3.1 The primal problem

we rewrite Equation 7.22 as the following

J(w) = (y (cid:0) Xw)T (y (cid:0) Xw) + l∥w∥2

(14.21)

and its solution is given by Equation 7.23.

14.4.3.2 The dual problem

Equation 14.21 is not yet in the form of inner products.
However, using the matrix inversion lemma (Equation
4.107 TODO) we rewrite the ridge estimate as follows

w = X T (XX T + lI N)(cid:0)1y

(14.22)

which takes O(N3 + N2D) time to compute. This can be
advantageous if D is large. Furthermore, we see that we
can partially kernelize this, by replacing XX T with the
Gram matrix K. But what about the leading X T term?

Let us deﬁne the following dual variables:

(cid:11) = (K + lI N)(cid:0)1y

(14.23)

Then we can rewrite the primal variables as follows

w = X T (cid:11) =

N
(cid:229)
i=1

aixi

(14.24)

This tells us that the solution vector is just a linear sum
of the N training vectors. When we plug this in at test time
to compute the predictive mean, we get

y = f (x) =

N
(cid:229)
i=1

aixT

i x =

N
(cid:229)
i=1

aik(xi; x)

(14.25)

So we have succesfully kernelized ridge regression by
changing from primal to dual variables. This technique
can be applied to many other linear models, such as logis-
tic regression.

14.4.3.3 Computational cost

The cost of computing the dual variables (cid:11) is O(N3),
whereas the cost of computing the primal variables w is
O(D3). Hence the kernel method can be useful in high
dimensional settings, even if we only use a linear kernel
(c.f., the SVD trick in Equation 7.24). However, predic-
tion using the dual variables takes O(ND) time, while pre-
diction using the primal variables only takes O(D) time.
We can speedup prediction by making (cid:11) sparse, as we
discuss in Section 14.5.

83

If L is quadratic loss, this is equivalent to ridge regres-
sion, and if L is the log-loss deﬁned in Equation 6.3, this
is equivalent to logistic regression.

However, if we replace the loss function with some
other loss function, to be explained below, we can ensure
that the solution is sparse, so that predictions only depend
on a subset of the training data, known as support vec-
tors. This combination of the kernel trick plus a modiﬁed
loss function is known as a support vector machine or
SVM.

Note that SVMs are very unnatural from a probabilistic

point of view.

• First, they encode sparsity in the loss function rather

than the prior.

• Second, they encode kernels by using an algorithmic
trick, rather than being an explicit part of the model.
• Finally, SVMs do not result in probabilistic outputs,
which causes various difﬁculties, especially in the
multi-class classiﬁcation setting (see Section 14.5.2.4
TODO for details).

It is possible to obtain sparse, probabilistic, multi-class
kernel-based classiﬁers, which work as well or better than
SVMs, using techniques such as the L1VM or RVM, dis-
cussed in Section 14.3.2. However, we include a discus-
sion of SVMs, despite their non-probabilistic nature, for
two main reasons.

• First, they are very popular and widely used, so all stu-
dents of machine learning should know about them.
• Second, they have some computational advantages
over probabilistic methods in the structured output
case; see Section 19.7 TODO.

14.4.4 Kernel PCA

14.5.1 SVMs for classiﬁcation

TODO

14.5.1.1 Primal form

Representation

14.5 Support vector machines (SVMs)

H : y = f (x) = sign(wx + b)

(14.27)

In Section 14.3.2, we saw one way to derive a sparse ker-
nel machine, namely by using a GLM with kernel basis
functions, plus a sparsity-promoting prior such as ℓ1 or
ARD. An alternative approach is to change the objective
function from negative log likelihood to some other loss
function, as we discussed in Section 6.4.5. In particular,
consider the ℓ2 regularized empirical risk function
J(w; l) = (cid:229) i = 1NL(yi; ˆyi) + l∥w∥2

(14.26)

where ˆyi = wT xi + w0.

Evaluation

min
w;b

s:t:

∥w∥2

1
2
yi(wxi + b) ⩾ 1; i = 1; 2; : : : ; N (14.29)

(14.28)

14.5.1.2 Dual form

Representation

84

(

N
(cid:229)
i=1

H : y = f (x) = sign

Evaluation

)

aiyi(x (cid:1) xi) + b

(14.30)

14.5.1.5 Hinge Loss

Linear support vector machines can also be interpreted as
hinge loss minimization:

min
a

1
2

N
(cid:229)
i=1

N
(cid:229)
j=1

aiajyiy j(xi (cid:1) x j) (cid:0)

N
(cid:229)
i=1

ai(14.31)

min
w;b

N
(cid:229)
i=1

L(yi; f (xi)) + l∥w∥2

(14.45)

s:t:

aiyi = 0

N
(cid:229)
i=1
ai ⩾ 0; i = 1; 2; : : : ; N

(14.32)

(14.33)

where L(y; f (x)) is a hinge loss function:

{

L(y; f (x)) =

1 (cid:0) y f (x); 1 (cid:0) y f (x) > 0
1 (cid:0) y f (x) ⩽ 0
0;

(14.46)

14.5.1.3 Primal form with slack variables

Representation

Proof. We can write equation 14.45 as equations 14.35 (cid:24)
14.37.

Deﬁne slack variables

H : y = f (x) = sign(wx + b)

(14.34)

xi ≜ 1 (cid:0) yi(w (cid:1) xi + b); xi ⩾ 0

(14.47)

Evaluation

min
w;b

s:t:

C

N
(cid:229)
i=1

xi +

∥w∥2

1
2
yi(wxi + b) ⩾ 1 (cid:0) xi
xi ⩾ 0;

i = 1; 2; : : : ; N

14.5.1.4 Dual form with slack variables

(14.35)

(14.36)

(14.37)

Then w; b; xi satisfy the constraints 14.35 and 14.36.

And objective function 14.37 can be written as

min
w;b

N
(cid:229)
i=1

xi + l∥w∥2

If l =

1
2C

, then

(

)

1
C

min
w;b

C

N
(cid:229)
i=1

xi +

1
2

∥w∥2

(14.48)

Representation

(

N
(cid:229)
i=1

H : y = f (x) = sign

Evaluation

)

It is equivalent to equation 14.35.

aiyi(x (cid:1) xi) + b

(14.38)

14.5.1.6 Optimization

min
a

1
2

N
(cid:229)
i=1

N
(cid:229)
j=1

aiajyiy j(xi (cid:1) x j) (cid:0)

QP, SMO

N
(cid:229)
i=1

ai(14.39)

s:t:

aiyi = 0

N
(cid:229)
i=1
0 ⩽ ai ⩽ C; i = 1; 2; : : : ; N

(14.40)

14.5.2 SVMs for regression

(14.41)

14.5.2.1 Representation

ai = 0 ) yi(w (cid:1) xi + b) ⩾ 1
ai = C ) yi(w (cid:1) xi + b) ⩽ 1
0 < ai < C ) yi(w (cid:1) xi + b) = 1

(14.42)
(14.43)

(14.44)

14.5.2.2 Evaluation

H : y = f (x) = wT x + b

(14.49)

J(w) = C

N
(cid:229)
i=1

L(yi; f (xi)) + +

∥w∥2

1
2

(14.50)

where L(y; f (x)) is a epsilon insensitive loss function:

L(y; f (x)) =

{
0
jy (cid:0) f (x)j (cid:0) e ; otherwise

; jy (cid:0) f (x)j < e

(14.51)

and C = 1=l is a regularization constant.

This objective is convex and unconstrained, but not dif-
ferentiable, because of the absolute value function in the
loss term. As in Section 13.4 TODO, where we discussed
the lasso problem, there are several possible algorithms
we could use. One popular approach is to formulate the
problem as a constrained optimization problem. In partic-
ular, we introduce slack variables to represent the degree
to which each point lies outside the tube:

yi (cid:20) f (xi) + e+ x+
i
yi (cid:21) f (xi) (cid:0) e(cid:0) x(cid:0)
i

Given this, we can rewrite the objective as follows:

J(w) = C

N
(cid:229)
i=1

(x+

i + x(cid:0)

i ) + +

∥w∥2

1
2

(14.52)

This is a standard quadratic problem in 2N + D + 1 vari-
ables.

14.5.3 Choosing C

SVMs for both classiﬁcation and regression require that
you specify the kernel function and the parameter C. Typ-
ically C is chosen by cross-validation. Note, however, that
C interacts quite strongly with the kernel parameters. For
example, suppose we are using an RBF kernel with pre-
cision g = 1
2s2 . If g = 5, corresponding to narrow ker-
nels, we need heavy regularization, and hence small C(so
l = 1=Cis big). If g = 1, a larger value of Cshould be
used. So we see that g and C are tightly coupled. This is
illustrated in Figure 14.2, which shows the CV estimate
of the 0-1 risk as a function of C and g.

The authors of libsvm recommend (Hsu et al. 2009)
using CV over a 2d grid with values C 2 f25; 23; (cid:1) (cid:1) (cid:1) ; 215g
and g 2 f215; 213; (cid:1) (cid:1) (cid:1) ; 23g. In addition, it is important to
standardize the data ﬁrst, for a spherical Gaussian kernel
to make sense.

To choose C efﬁciently, one can develop a path follow-
ing algorithm in the spirit of lars (Section 13.3.4 TODO).
The basic idea is to start with l large, so that the margin
1=∥w(l)∥ is wide, and hence all points are inside of it
and have ai = 1. By slowly decreasing l, a small set of
points will move from inside the margin to outside, and
their ai values will change from 1 to 0, as they cease to
be support vectors. When l is maximal, the function is
completely smoothed, and no support vectors remain. See
(Hastie et al. 2004) for the details.

85

(a)

(b)

Fig. 14.2: (a) A cross validation estimate of the 0-1 error
for an SVM classiﬁer with RBF kernel with different
precisions g = 1=(2s2) and different regularizer
g = 1=C, applied to a synthetic data set drawn from a
mixture of 2 Gaussians. (b) A slice through this surface
for g = 5 The red dotted line is the Bayes optimal error,
computed using Bayes rule applied to the model used to
generate the data. Based on Figure 12.6 of (Hastie et al.
2009).

14.5.4 A probabilistic interpretation of

SVMs

TODO see MLAPP Section 14.5.5

14.5.5 Summary of key points

Summarizing the above discussion, we recognize that
SVM classiﬁers involve three key ingredients: the kernel
trick, sparsity, and the large margin principle. The kernel
trick is necessary to prevent underﬁtting, i.e., to ensure
that the feature vector is sufﬁciently rich that a linear
classiﬁer can separate the data. (Recall from Section
14.2.3 that any Mercer kernel can be viewed as implicitly
deﬁning a potentially high dimensional feature vector.) If
the original features are already high dimensional (as in
many gene expression and text classiﬁcation problems),
it sufﬁces to use a linear kernel, k(x; x′) = xT x′ , which
is equivalent to working with the original features.

The sparsity and large margin principles are necessary
to prevent overﬁtting, i.e., to ensure that we do not use all

Method Opt. w

Opt. Sparse Prob. Multiclass Non-Mercer Section

EB No
L2VM Convex
L1VM Convex
CV Yes
RVM Not convex EB Yes
CV Yes
SVM Convex
EB No
GP

N/A

Yes Yes
Yes Yes
Yes Yes
No
Yes Yes

Yes
Yes
Yes
Indirectly No
No

14.3.2
14.3.2
14.3.2
14.5
15

Table 14.1: Comparison of various kernel based
classiﬁers. EB = empirical Bayes, CV = cross validation.
See text for details

14.7 Kernels for building generative models

TODO

86

the basis functions. These two ideas are closely related to
each other, and both arise (in this case) from the use of the
hinge loss function. However, there are other methods of
achieving sparsity (such as ℓ1), and also other methods of
maximizing the margin(such as boosting). A deeper dis-
cussion of this point takes us outside of the scope of this
book. See e.g., (Hastie et al. 2009) for more information.

14.6 Comparison of discriminative kernel

methods

We have mentioned several different methods for classiﬁ-
cation and regression based on kernels, which we summa-
rize in Table 14.1. (GP stands for Gaussian process, which
we discuss in Chapter 15 TODO.) The columns have the
following meaning:

• Optimize w: a key question is whether the objective
J(w = (cid:0) log p(Djw) (cid:0) log p(w)) is convex or not.
L2VM, L1VM and SVMs have convex objectives.
RVMs do not. GPs are Bayesian methods that do not
perform parameter estimation.

• Optimize kernel: all the methods require that one tune
the kernel parameters, such as the bandwidth of the
RBF kernel, as well as the level of regularization. For
methods based on Gaussians, including L2VM, RVMs
and GPs, we can use efﬁcient gradient based optimiz-
ers to maximize the marginal likelihood. For SVMs,
and L1VM, we must use cross validation, which is
slower (see Section 14.5.3).

• Sparse: L1VM, RVMs and SVMs are sparse kernel
methods, in that they only use a subset of the train-
ing examples. GPs and L2VM are not sparse: they use
all the training examples. The principle advantage of
sparsity is that prediction at test time is usually faster.
In addition, one can sometimes get improved accuracy.
• Probabilistic: All the methods except for SVMs pro-
duce probabilistic output of the form p(yjx). SVMs
produce a conﬁdence value that can be converted to
a probability, but such probabilities are usually very
poorly calibrated (see Section 14.5.2.3 TODO).

• Multiclass: All the methods except for SVMs naturally
work in the multiclass setting, by using a multinoulli
output instead of Bernoulli. The SVM can be made into
a multiclass classiﬁer, but there are various difﬁculties
with this approach, as discussed in Section 14.5.2.4
TODO.

• Mercer kernel: SVMs and GPs require that the kernel

is positive deﬁnite; the other techniques do not.

Chapter 15
Gaussian processes

15.1 Introduction

15.3 GPs meet GLMs

15.4 Connection with other methods

15.5 GP latent variable model

15.6 Approximation methods for large

datasets

In supervised learning, we observe some inputs xi and
some outputs yi. We assume that yi = f (xi), for some un-
known function f , possibly corrupted by noise. The opti-
mal approach is to infer a distribution over functions given
the data, p( f jD), and then to use this to make predictions
given new inputs, i.e., to compute

∫

p(yjx; D) =

p(yj f ; x)p( f jD)d f

(15.1)

Up until now, we have focussed on parametric repre-
sentations for the function f , so that instead of inferring
p( f jD), we infer p((cid:18)jD). In this chapter, we discuss a
way to perform Bayesian inference over functions them-
selves.

Our approach will be based on Gaussian processes or
GPs. A GP deﬁnes a prior over functions, which can be
converted into a posterior over functions once we have
seen some data.

It turns out that, in the regression setting, all these com-
putations can be done in closed form, in O(N3) time. (We
discuss faster approximations in Section 15.6.) In the clas-
siﬁcation setting, we must use approximations, such as the
Gaussian approximation, since the posterior is no longer
exactly Gaussian.

GPs can be thought of as a Bayesian alternative to
the kernel methods we discussed in Chapter 14, includ-
ing L1VM, RVM and SVM.

15.2 GPs for regression

Let the prior on the regression function be a GP, denoted
by

f (x) (cid:24) GP(m(x); k(x; x′))
(15.2)
where m(x is the mean function and k(x; x′) is the kernel
or covariance function, i.e.,

m(x = E[ f (x)]

k(x; x′) = E[( f (x) (cid:0) m(x))( f (x) (cid:0) m(x))T ]

(15.3)

(15.4)

where k is a positive deﬁnite kernel.

87

Chapter 16
Adaptive basis function models

16.1 AdaBoost

16.1.3.3 Algorithm

16.1.1 Representation

y = sign( f (x)) = sign

)

amGm(x)

(16.1)

(

m
(cid:229)
i=1

where Gm(x) are sub classiﬁers.

16.1.2 Evaluation

1. Initialize

the weights’

distribution

of

training

data(when m = 1)

D0 = (w11; w12; (cid:1) (cid:1) (cid:1) ; w1n) = (

1
N

;

1
N

; (cid:1) (cid:1) (cid:1) ;

1
N

)

2. Iterate over m = 1; 2; : : : ; M

(a) Use training data with current weights’ distribu-

tion Dm to get a classiﬁer Gm(x)

(b) Compute the error rate of Gm(x) over the

training data

L(y; f (x)) = exp[(cid:0)y f (x)] i.e., exponential loss function

em = P(Gm(xi) ̸= yi) =

N
(cid:229)
i=1

wmiI(Gm(xi) ̸= yi) (16.4)

(am; Gm(x)) = arg min
a;G

exp [(cid:0)yi( fm(cid:0)1(xi) + aG(xi))]

(16.2)
Deﬁne ¯wmi = exp [(cid:0)yi( fm(cid:0)1(xi)], which is constant

N
(cid:229)
i=1

w.r.t. a; G

(am; Gm(x)) = arg min
a;G

N
(cid:229)
i=1

¯wmi exp ((cid:0)yiaG(xi))

(16.3)

16.1.3 Optimization

16.1.3.1 Input

D = f(x1; y1); (x2; y2); : : : ; (xN; yN)g
where xi 2 RD; yi 2 f(cid:0)1; +1g
Weak classiﬁers fG1; G2; : : : ; Gmg

16.1.3.2 Output

Final classiﬁer: G(x)

(c) Compute the coefﬁcient of classiﬁer Gm(x)

am =

1
2

log

1 (cid:0) em
em

(16.5)

(d) Update the weights’ distribution of training data

wm+1;i =

wmi
Zm

exp((cid:0)amyiGm(xi))

(16.6)

where Zm is the normalizing constant

Zm =

N
(cid:229)
i=1

wmi exp((cid:0)amyiGm(xi))

(16.7)

3. Ensemble M weak classiﬁers
[

]

G(x) = sign f (x) = sign

M
(cid:229)
m=1

amGm(x)

(16.8)

16.1.4 The upper bound of the training

error of AdaBoost

Theorem 16.1. The upper bound of the training error of
AdaBoost is

1
N

N
(cid:229)
i=1

I(G(xi) ̸= yi) (cid:20) 1
N

N
(cid:229)
i=1

exp((cid:0)yi f (xi)) =

M
(cid:213)
m=1

Zm

(16.9)

89

90

Note: the following equation would help proof this the-

orem

wmi exp((cid:0)amyiGm(xi)) = Zmwm+1;i

(16.10)

Chapter 17
Hidden markov Model

17.1 Introduction

17.2 Markov models

91

Chapter 18
State space models

93

Chapter 19
Undirected graphical models (Markov random ﬁelds)

95

Chapter 20
Exact inference for graphical models

97

Chapter 21
Variational inference

99

Chapter 22
More variational inference

101

Chapter 23
Monte Carlo inference

103

Chapter 24
Markov chain Monte Carlo (MCMC)inference

24.1 Introduction

In Chapter 23, we introduced some simple Monte Carlo
methods, including rejection sampling and importance
sampling. The trouble with these methods is that they do
not work well in high dimensional spaces. The most pop-
ular method for sampling from high-dimensional distribu-
tions is Markov chain Monte Carlo or MCMC.

The basic idea behind MCMC is to construct a Markov
chain (Section 17.2) on the state space X whose station-
ary distribution is the target density p(cid:3)(x) of interest (this
may be a prior or a posterior). That is, we perform a ran-
dom walk on the state space, in such a way that the frac-
tion of time we spend in each state x is proportional to
p(cid:3)(x). By drawing (correlated!) samples x0; x1; x2; (cid:1) (cid:1) (cid:1)
from the chain, we can perform Monte Carlo integration
wrt p(cid:3).

24.2 Metropolis Hastings algorithm

24.3 Gibbs sampling

24.4 Speed and accuracy of MCMC

24.5 Auxiliary variable MCMC *

105

Chapter 25
Clustering

107

Chapter 26
Graphical model structure learning

109

Chapter 27
Latent variable models for discrete data

27.1 Introduction

27.2 Distributed state LVMs for discrete

data

In this chapter, we are concerned with latent variable mod-
els for discrete data, such as bit vectors, sequences of cat-
egorical variables, count vectors, graph structures, rela-
tional data, etc. These models can be used to analyse vot-
ing records, text and document collections, low-intensity
images, movie ratings, etc. However, we will mostly focus
on text analysis, and this will be reﬂected in our terminol-
ogy.

Since we will be dealing with so many different kinds
of data, we need some precise notation to keep things
clear. When modeling variable-length sequences of cat-
egorical variables (i.e., symbols or tokens), such as words
in a document, we will let yil 2 f1; (cid:1) (cid:1) (cid:1) ;V g represent the
identity of the l’th word in document i,where V is the
number of possible words in the vocabulary. We assume
l = 1 : Li, where Li is the (known) length of document i,
and i = 1 : N, where N is the number of documents.

We will often ignore the word order, resulting in a bag
of words. This can be reduced to a ﬁxed length vector of
counts (a histogram). We will use niv 2 f0; 1; (cid:1) (cid:1) (cid:1) ; Lig to
denote the number of times word v occurs in document i,
for v = 1 : V . Note that the N (cid:2)V count matrix N is often
large but sparse, since we typically have many documents,
but most words do not occur in any given document.

In some cases, we might have multiple different bags of
words, e.g., bags of text words and bags of visual words.
These correspond to different channels or types of fea-
tures. We will denote these by yirl, for r = 1 : R(the num-
ber of responses) and l = 1 : Lir. If Lir = 1,it means we
have a single token (a bag of length 1); in this case, we
just write yir 2 f1; (cid:1) (cid:1) (cid:1) ;Vrg for brevity. If every channel is
just a single token, we write the ﬁxed-size response vec-
tor as yi;1:R; in this case, the N (cid:2) R design matrix Y will
not be sparse. For example, in social science surveys, yir
could be the response of personito the r’th multi-choice
question.

Out goal is to build joint probability models of p(yi)
or p(ni) using latent variables to capture the correlations.
We will then try to interpret the latent variables, which
provide a compressed representation of the data. We pro-
vide an overview of some approaches in Section 27.2
TODO, before going into more detail in later sections.

111

Chapter 28
Deep learning

113

Appendix A
Optimization methods

A.1 Convexity

A.2 Gradient descent

Deﬁnition A.1. (Convex set) We say aset S is convex if
for any x1; x2 2 S, we have

A.2.1 Stochastic gradient descent

lx1 + (1 (cid:0) l)x2 2 S; 8l 2 [0; 1]

(A.1)

Deﬁnition A.2. (Convex function) A function f (x) is
called convex if its epigraph(the set of points above the
function) deﬁnes a convex set. Equivalently, a function
f (x) is called convex if it is deﬁned on a convex set and
if, for any x1; x2 2 S, and any l 2 [0; 1], we have

f (lx1 + (1 (cid:0) l)x2) (cid:20) l f (x1) + (1 (cid:0) l) f (x2)

(A.2)

Deﬁnition A.3. A function f (x) is said to be strictly con-
vex if the inequality is strict

f (lx1 + (1 (cid:0) l)x2) < l f (x1) + (1 (cid:0) l) f (x2)

(A.3)

Deﬁnition A.4. A function f (x) is said to be (strictly)
concave if (cid:0) f (x) is (strictly) convex.

input : Training data D = f(xi; yi)ji = 1 : Ng
output: A linear model: yi = (cid:18)T x
w   0; b   0; k   0;
while no mistakes made within the for loop do

for i   1 to N do

if yi(w (cid:1) xi + b) (cid:20) 0 then
w   w + hyixi;
b   b + hyi;
k   k + 1;

end

end

end

Algorithm 5: Stochastic gradient descent

Theorem A.1. If f (x) is twice differentiable on [a; b] and
f ′′(x) (cid:21) 0 on [a; b] then f (x) is convex on [a; b].

A.2.2 Batch gradient descent

Proposition A.1. log(x) is strictly convex on (0; ¥).

A.2.3 Line search

Intuitively, a (strictly) convex function has a bowl
shape, and hence has a unique global minimum x(cid:3) cor-
responding to the bottom of the bowl. Hence its second
derivative must be positive everywhere, d2
dx2 f (x) > 0. A
twice-continuously differentiable, multivariate function
f is convex iff its Hessian is positive deﬁnite for all x.
In the machine learning context, the function f often
corresponds to the NLL.

Models where the NLL is convex are desirable, since
this means we can always ﬁnd the globally optimal MLE.
We will see many examples of this later in the book. How-
ever, many models of interest will not have concave like-
lihoods. In such cases, we will discuss ways to derive lo-
cally optimal parameter estimates.

The line search1 approach ﬁrst ﬁnds a descent direc-
tion along which the objective function f will be reduced
and then computes a step size that determines how far x
should move along that direction. The descent direction
can be computed by various methods, such as gradient
descent(Section A.2), Newton’s method(Section A.4) and
Quasi-Newton method(Section A.5). The step size can be
determined either exactly or inexactly.

1 http://en.wikipedia.org/wiki/Line_search

115

116

A.2.4 Momentum term

A.3 Lagrange duality

A.3.1 Primal form

Consider the following, which we’ll call the primal opti-
mization problem:

A Optimization methods

The idea is to replace H (cid:0)1

k with a approximation Bk,

which satisﬁes the following properties:

1. Bk must be symmetric
2. Bk must satisﬁes the quasi-Newton condition, i.e.,

gk+1 (cid:0) gk = Bk+1(xk+1 (cid:0) xk).
Let yk = gk+1 (cid:0) gk, (cid:14)k = xk+1 (cid:0) xk, then

Bk+1yk = (cid:14)k

(A.8)

3. Subject to the above, Bk should be as close as possible

xyz

(A.4)

to Bk(cid:0)1.

A.3.2 Dual form

A.4 Newton’s method

f (x) (cid:25) f (xk) + gT

k (x (cid:0) xk) +

1
2

Note that we did not require that Bk be positive deﬁ-
nite. That is because we can show that it must be positive
deﬁnite if Bk(cid:0)1 is. Therefore, as long as the initial Hes-
sian approximation B0 is positive deﬁnite, all Bk are, by
induction.

(x (cid:0) xk)T H k(x (cid:0) xk)

A.5.1 DFP

where gk ≜ g(xk) = f ′(xk); H k ≜ H(xk);
¶2 f
¶xi¶x j

H(x) ≜

[

]

D(cid:2)D

(Hessian matrix)

f ′(x) = gk + H k(x (cid:0) xk) = 0 )
xk+1 = xk (cid:0) H (cid:0)1

k gk

Updating rule:

Bk+1 = Bk + P k + Qk

(A.9)

(A.5)

(A.6)

From Equation A.8 we can get

Bk+1yk = Bkyk + P kyk + Qkyk = (cid:14)k

To make the equation above establish, just let

Initialize x0
while (!convergency) do

Evaluate gk = (cid:209) f (xk)
Evaluate Hk = (cid:209)2 f (xk)
(cid:0)1
dk = (cid:0)H
k gk
Use line search to ﬁnd step size hk along dk
xk+1 = xk + hkdk

end

Algorithm 6: Newtons method for minimizing a strictly
convex function

P kyk = (cid:14)k
Qkyk = (cid:0)Bkyk

In DFP algorithm, P k and Qk are

P k =

Qk = (cid:0)

(cid:14)k(cid:14)T
k
(cid:14)T
k yk
BkykyT
yT
k Bkyk

k Bk

(A.10)

(A.11)

A.5 Quasi-Newton method

A.5.2 BFGS

From Equation A.5 we can infer out the quasi-Newton
condition as follows:

Use Bk as a approximation to H k, then the quasi-Newton
condition becomes

f ′(x) (cid:0) gk = H k(x (cid:0) xk)
gk(cid:0)1 (cid:0) gk = H k(xk(cid:0)1 (cid:0) xk) )
gk (cid:0) gk(cid:0)1 = H k(xk (cid:0) xk(cid:0)1)
gk+1 (cid:0) gk = H k+1(xk+1 (cid:0) xk)

Bk+1(cid:14)k = yk

(A.12)

The updating rule is similar to DFP, but P k and Qk are

different. Let

(quasi-Newton condition)

(A.7)

A.5 Quasi-Newton method

117

P k(cid:14)k = yk
Qk(cid:14)k = (cid:0)Bk(cid:14)k

Then

P k =

ykyT
k
yT
k (cid:14)k
Bk(cid:14)k(cid:14)T
(cid:14)T
k Bk(cid:14)k

k Bk

Qk = (cid:0)

(A.13)

(A.14)

A.5.3 Broyden

Broyden’s algorithm is a linear combination of DFP and
BFGS.

Glossary

feture vector A feture vector to represent one data.

loss function a function that maps an event onto a real
number intuitively representing some ”cost” associated
with the event.

glossary term Write here the description of the glos-
sary term. Write here the description of the glossary term.
Write here the description of the glossary term.

119

